我尝试使用Redux在React JS中创建一个登录页面,在获得成功的登录响应后,我试图将用户重定向到主页('/'路径),但它在动作层中引发错误:
doLogin:failure TypeError:无法读取undefined的属性'apply' at listener(createTransitionManager.js:46) 在createTransitionManager.js:65 在Array.forEach() at Object.notifyListeners(createTransitionManager.js:64) at setState(createBrowserHistory.js:78) 在createBrowserHistory.js:169 at Object.confirmTransitionTo(createTransitionManager.js:36) at Object.push(createBrowserHistory.js:149) 在user.js:25
user.js文件
export const doLogin = (email, password) => {
return (dispatch) => {
loginService(email, password)
.then(res => {
console.log('doLogin: success ',res)
if(res.error) dispatch(loginFailure(res))
else {
if(res && res.token) localStorage.setItem('user', JSON.stringify(res))
dispatch(loginSuccess(res))
history.push('/')
}
})
.catch(error => {
console.log('doLogin: failure ',error)
dispatch(loginFailure(error))
})
}
}
答案 0 :(得分:0)
我建议使用https://github.com/reactjs/react-router-redux,然后这是一个简单的import { push } from 'react-router-redux'; dispatch(push('/path'));
。
答案 1 :(得分:0)
你试过https://www.npmjs.com/package/history模块吗? 在React项目中实现起来非常容易。
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
将以上代码添加到index.js文件中,并将其作为props传递给所有组件。
将历史作为道具传递:
<Router history={history}>
<App />
</Router>
访问所有组件中的历史记录,如下所示:
this.props.history.push('/login');
希望它对你有所帮助。干杯!!