如何分派一个动作来改变反应组件中的内部状态

How to dispatch an action to change the inner state in a react component

我可以在 redux 中调度一个动作来改变 react 组件的内部状态吗?

我有一个由反应状态管理的状态,我想在 redux 的中间件中做一些异步的事情,这样我就可以在一个地方管理所有的副作用。但是,我想在完成异步调用后更改反应的内部状态,并且我不想通过 redux 管理此状态(您需要将太多东西传递到操作中)。有没有办法启动一个动作来通过 redux 改变反应状态?谢谢。

您可以使用 componentWillReceiveProps 生命周期挂钩来完成。

因此,您应该使用 react-redux 中的 connect 连接到更新,然后更新您的本地状态。

例如:

SomeContainer.jsx

import React from 'react';
import { connect } from 'react-redux';
import { yourCustomAsyncAction } from '../actions';
import SomeComponent from './components';

const mapStateToProps = state => {
  return {
    someValue: state.someState.someValue
  };
};

export default connect(mapStateToProps, { yourCustomAsyncAction })(SomeComponent));

SomeComponent.jsx

import React, { Component } from 'react';

class SomeComponent extends Component {
   constructor(props) {
     super(props);

     this.state = {
       someLocalValue: '',
     }
   }

   componentWillReceiveProps(nextProps) {
       // someValue - value which we passed from redux in container
       const { someValue } = nextProps;

      if (someValue !== this.state.someLocalValue) {
          this.setState({ someLocalValue: someValue });
      }
   }

   render() {
      return <div> Here will be updated value via Redux: {this.state.someLocalValue} </div>
   }

}

export default SomeComponent;

注意: componentWillReceiveProps 将从 React 16.3 版(应该很快发布)开始弃用,并将在 17 版中删除。引入了名为 getDerivedStateFromProps 的新静态方法。查看更多 here.

希望对您有所帮助。