简体   繁体   English

如何将在React-Router中传递的状态迁移到Redux Store?

[英]How to migrate state passed in React-Router to Redux Store?

So far, I have been using React with React-Router and when passing data between URL s, I have been passing the state as 到目前为止,我一直在使用ReactReact-Router一起使用React ,并且在URL之间传递数据时,我一直在传递状态为

this.props.history.push(Routes.transactionEdit, this.state.transaction);  

This is documented here 在这里记录

and in the Component, I would use it as 在组件中,我将其用作

constructor(props) {
    super(props);
    this.state = {
        userId: props.history.location.state.userId,
        transactionId: props.history.location.state.id,
        createdAt: props.history.location.state.createdAt,
        name: props.history.location.state.name,
        amount: props.history.location.state.amount,
    }
}

However, I learned that managing state in Redux is a better idea and it helps test the store separately from how the views look. 但是,我了解到在Redux中管理状态是一个更好的主意,它有助于与视图外观分开测试商店。 and I liked that idea because I care about the clean-testable code. 我喜欢这个主意,因为我关心可清洁测试的代码。

I started refactoring code and for many parts where I need data from the database, I was able to migrate the code using thunk pattern. 我开始重构代码,对于需要从数据库获取数据的许多部分,我能够使用thunk模式迁移代码。 However, with this use case where the state is sent as part of history.push , I don't know how to put this state into the Redux Store. 但是,在这种用例中,状态是作为history.push一部分发送的,我不知道如何将该状态放入Redux Store。

Question
How do I migrate the state in this.props.history.push(Routes.transactionEdit, this.state.transaction); 如何在this.props.history.push(Routes.transactionEdit, this.state.transaction);迁移状态this.props.history.push(Routes.transactionEdit, this.state.transaction); (during push) to the Redux store, so that it can be managed outside of React Component? (在推送期间)到Redux存储,以便可以在React Component之外对其进行管理?

Thanks 谢谢

You'll need to setup a specific action that is specifically meant for taking a component's state and pushes it to Redux's store. 您需要设置一个特定的action ,该操作专门用于获取组件的状态并将其推送到Redux的存储。 Of course you'll need to have your reducer respond appropriately to that action. 当然,您需要使减速器对该动作做出适当的响应。 If youre new to Redux, this might be opening a big can of worms. 如果您是Redux的新手,这可能会打开一大堆蠕虫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM