简体   繁体   English

如何在react-redux中更新存储状态?

[英]How to update store state in react-redux?

I'm working on a component in React (with Redux) that has the requirements to: 我正在研究React(使用Redux)中的一个组件,它具有以下要求:

  1. Retreive data from an API endpoint. 从API端点检索数据。
  2. Display that data, with one field being editable. 显示该数据,一个字段可编辑。
  3. If the editable field is edited, it has to update the rest of the fields and send them to a different endpoint. 如果编辑的字段进行编辑 ,有更新的字段的其余部分,并将它们发送到不同的端点。

I'm having trouble grasping how exactly I should implement the editing using the Redux metodology. 我无法理解我应该如何使用Redux方法实现编辑。

Here is a simplified component: 这是一个简化的组件:

class MyComponent extends Component {
  constructor(...args) {
    super(...args);
    this.props.dispatch(getDataFromEndpoint());
  }
  editField(e) {
    this.props.dispatch(editFieldAction(e.target.value));
  }
  render() {
    return (
      <div>
        <input type="text" defaultValue={this.props.data.editableField} onChange={this.editField} />
        {
          this.props.data.uneditable.map(x => {
            return (
              <span>{x}</span>
            );
          })
        }
      </div>
      );
  }
}

const mapProps = state => {
  const { data } = state.endpointData;
  return { data };
}

export default connect(mapProps)(MyComponent);

Note that I've written this component as an example, it might have errors, but you should get the point. 请注意,我已将此组件编写为示例,它可能有错误,但您应该明白这一点。 Whenever this.editField is called, it should update every value in this.props.data.uneditable . 每当this.editField ,它都应该更新this.props.data.uneditable每个值。

What is the correct way to do this? 这样做的正确方法是什么?

In a sense these questions all boil down to: How do I wire up my component(s) to read from (and write to) Redux state. 从某种意义上说,这些问题都归结为:如何连接我的组件以读取(和写入)Redux状态。 This is essentially the purpose of redux-react's connect function (which you have in the bottom of your example). 这基本上是redux-react的连接功能的目的(你在示例的底部有)。 You use the first parameter, mapStateToProps, to be able to read from state. 您可以使用第一个参数mapStateToProps来从状态读取。 You use the second parameter (that you don't have yet) - mapDispatchToProps - to provide the means to write to it. 您使用第二个参数(您还没有) - mapDispatchToProps - 提供写入它的方法。 Dispatching an action is how you update Redux state. 调度操作是您更新Redux状态的方式。

You can simply use this.props.dispatch, but it is more idiomatic to use mapDispatchToProps, which simply provides an object where each property is a function which calls dispatch with the appropriate action creator. 可以简单地使用this.props.dispatch,但使用mapDispatchToProps更为惯用,它只提供一个对象,其中每个属性都是一个函数,它使用适当的动作创建者调用dispatch。 You might accept as a parameter for example the data which you are looking to update your store with. 您可以接受作为参数,例如您要更新商店的数据。

What ends up happening is in your component when you want to update the state (say from an input), you use the methods you wired up with mapDispatchToProps to dispatch an action with the relevant data (the updated input value), and then write a reducer which responds to the action and updates the relevant part of your store. 当您想要更新状态(例如从输入中)时,最终发生的事情是在您的组件中,您使用与mapDispatchToProps连接的方法来调度具有相关数据的操作(更新的输入值),然后编写一个reducer响应操作并更新商店的相关部分。 Redux will then trigger a re-render in your component and it will pull the updated data from the store. 然后Redux将在您的组件中触发重新渲染,它将从商店中提取更新的数据。

Async actions are handled a bit differently of course (which is what your API calls will be), because they typically have several changes to state being spread out over time. 当然,异步操作的处理方式略有不同(这是您的API调用的方式),因为它们通常会随着时间的推移对状态进行多次更改。 Usually something like: 通常类似于:

  • Start the API request. 启动API请求。 (Dispatch an action to..) Set a flag somewhere in your state indicating the API request is 'in transit'. (将动作发送到..)在您所在州的某处设置一个标志,表示API请求是“正在传输”。
  • Receive the response. 收到回复。 (Dispatch again to..) Set a flag somewhere saying the request is finished, and if it was successful, store your response data somewhere. (再次发送给..)在某处设置一个标志,表示请求已完成,如果成功,则将响应数据存储在某处。 If it was an error, store the error (or just the fact there was an error). 如果是错误,请存储错误(或者只是存在错误)。

I would recommend redux-thunk for this purpose, since at least for me it is the easiest to understand and work with out of all the various libraries and methods to handle async with redux. 我建议为此目的使用redux-thunk,因为至少对我而言,最容易理解并使用所有各种库和方法来处理与redux的异步。 Instead of dispatching an object which contains the data describing the action, you instead dispatch a function, which means you can write any kind of logic you would like, allowing you to dispatch several times for example. 您不是调度包含描述操作的数据的对象,而是调度一个函数,这意味着您可以编写任何类型的逻辑,例如,允许您多次调度。 This makes it easy to do the steps outlined above.. simply have a function which calls your API, and in the callback (or .then() method) you dispatch an action with the result. 这样可以很容易地执行上面列出的步骤。只需要一个调用API的函数,然后在回调(或.then()方法中)中调度一个带有结果的操作。

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

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