Redux-React-route v4/v5 push() 在 thunk action 中不起作用



index.js直接推送或抛出调度效果很好:

...
import { push } from 'react-router-redux'
const browserHistory = createBrowserHistory()
export const store = createStore(
rootReducer,
applyMiddleware(thunkMiddleware, routerMiddleware(browserHistory))
)
// in v5 this line is deprecated
export const history = syncHistoryWithStore(browserHistory, store)
history.push('/any') // works well
store.dispatch(push('/any')) // works well
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>
), document.getElementById('root'))

App.js

class App extends Component {
render() {
return (
<div className="app">
<Switch>
<Route path="/" component={Main} />
<Route path="/any" component={Any} />
</Switch>
</div>
);
}
}
export default withRouter(connect(/*...*/)(App))

但是redux-thunk操作中,所有尝试都以重写 URL 结束,但没有重新渲染

...
export function myAction(){
return (dispatch) => {
// fetch something and then I want to redirect...
history.push('/any') // change url but not re-render
dispatch(push('/any')) // change url but not re-render
store.dispatch(push('/any')) // change url but not re-render
}
}

myAction在内部调用 fetch((,成功后应重定向。

如果我在组件内部运行this.props.history.push('/any')它可以工作! 但我需要在成功fetch()在 thunk 操作中运行重定向

我试图用withRouterRoute包装所有组件,但没有帮助。

history对象注入组件并使用如下所示的 push:

import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
@withRouter
@connect(({auth})=>({auth}))
class App extends Component {
// on redux state change
componentWillReceiveProps(nextProps) {
if(!nextProps.auth)
this.props.history.push('/login')
}
render() {
return (
<div>
<Button
// on button click
onClick={this.props.history.push('/')}
>
Home page
</Button>
</div>
);
}
}

我通过将成功 fetch(( 的状态委托给组件(感谢@oklas(来解决此问题,其中history.push()<Redirect>工作:

{this.props.fetchSuccessfull && <Redirect to="/any" />}

但是仍然通过直接从 thunk 操作调用 push(( 来等待更好的解决方案。

好吧,让我通过将调度中的 history 对象传递给操作来提交另一个不完美的解决方案。我想这更像是一个初学者的解决方案,但恕我直言,它很容易理解(因此易于维护,这是软件开发中最重要的事情(

使用使所有 React-compoments 在其道具中都有历史记录。非常方便。但是,正如问题描述所述,您希望它在 React 组件之外,就像 Redux-Thunk 上的操作一样。

我没有回到<路由器>,而是选择坚持使用BrowserRouter。

  • 历史对象不能在 React 组件之外访问
  • 我不喜欢回到<路由器>并使用类似react-router-redux的东西

剩下的唯一选项是将历史记录对象传递给操作。

在身份验证忘记密码组件中:

const submitHandler = (data) => {
dispatch(authActions.forgotpassword({data, history:props.history}));
}

在动作功能中

export const forgotpassword = ({forgotpasswordData, history}) => {
return async dispatch => {
const url = settings.api.hostname + 'auth/forgotpassword'; // Go to the API
const responseData = await fetch(
url,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(forgotpasswordData),
}
);
history.push('/auth/forgotpassword/success');
}
}

现在我们都在等待最终的优雅解决方案:-(

最新更新