问题描述:basename无法工作connected-react-router。
解决方法:
确保已正确配置basename参数。basename参数用于指定应用程序部署的基本URL路径。在React应用程序中,通常需要将basename参数设置为服务器上部署应用程序的目录。
import { ConnectedRouter } from 'connected-react-router';
import { createBrowserHistory } from 'history';
const history = createBrowserHistory({ basename: '/your-base-url' });
ReactDOM.render(
,
document.getElementById('root')
);
确保已正确设置服务器的路由配置。如果应用程序部署在子目录中,例如/your-base-url
,则需要确保服务器的路由配置正确指向该子目录。
例如,在使用Nginx作为服务器的情况下,需要在Nginx配置文件中添加以下代码片段:
location /your-base-url {
# 配置代理到React应用程序的端口
proxy_pass http://localhost:3000;
}
请根据您使用的服务器软件进行相应的配置。
确保路由链接使用正确的路径。如果您在应用程序中使用了组件或
history.push
方法来跳转到其他路由,确保路径是相对于basename的。
例如,在使用组件时,将
to
属性设置为相对于basename的路径:
import { Link } from 'react-router-dom';
const MyComponent = () => (
Go to other page
);
在使用history.push
方法时,将路径设置为相对于basename的路径:
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const goToOtherPage = () => {
history.push('/your-base-url/other-page');
};
return ;
};
通过以上解决方法,您应该能够解决basename无法工作的问题,并使connected-react-router正常工作。