jen*_*lky 5 reactjs react-router
嗨,我正在使用 react router v4。
我的 React 在端口 3000 上运行,而 express 服务器在端口 8080 上运行。下面代码的重定向部分将我带到localhost:3000/http://localhost:8080/auth/login.
我已经"proxy": "localhost:8080"在我的 React 的 package.json 中了。它不起作用。
我怎样才能从 重定向localhost:3000到localhost:8080/auth/login?
应用程序.js
class App extends Component {
constructor(props) {
super(props);
this.props.fetchProducts();
this.props.fetchUser();
}
render() {
return (
<Switch>
<Route exact path='/cart' render={() => this.props.isLoggedIn ?
<Checkout /> :
<Redirect to='http://localhost:8080/auth/login' />
} />
<Route exact path='/user/account/profile' render={() => <Profile />} />
<Route exact path='/' render={() => <MainPage />} />
</Switch>
);
}
}
Run Code Online (Sandbox Code Playgroud)
客户端的 package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^3.6.2",
"prop-types": "^15.6.2",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"react-router-dom": "^4.3.1",
"react-scripts": "^2.1.3",
"redux": "^4.0.0",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0"
},
"proxy": "http://localhost:8080",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Run Code Online (Sandbox Code Playgroud)
由于我无法使用react-router的Redirect来链接到/auth/login,我改变window.location.href了一个方法并返回null。
class App extends Component {
constructor(props) {
super(props);
this.props.fetchProducts();
this.props.fetchUser();
}
redirect = () => {
window.location.href = 'http://localhost:8080/auth/login';
// maybe can add spinner while loading
return null;
}
render() {
return (
<Switch>
<Route exact path='/cart' render={() =>
this.props.isLoggedIn ?
<Checkout /> :
this.redirect()
} />
<Route exact path='/user/account/profile' render={() => <Profile />} />
<Route exact path='/' render={() => <MainPage />} />
</Switch>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5975 次 |
| 最近记录: |