【问题标题】:How to dispatch an action to change the inner state in a react component如何调度一个动作来改变一个反应组件的内部状态
【发布时间】:2018-09-01 07:15:46
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    您可以使用componentWillReceiveProps 生命周期钩子来实现。

    因此,您应该使用来自react-reduxconnect 连接到更新,然后更新您的本地状态。

    例如:

    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

    希望它会有所帮助。

    【讨论】:

    • 感谢您的回答。我想在完成异步功能后设置状态:idx + 1。似乎我可以在 redux 中保留一个变量,例如“isLoaded”,以跟踪我是否成功完成了我的异步函数。但是我不知道如何根据这个来设置状态。
    • @leuction 在这种情况下,您可以在componentWillReceiveProps 中进行此操作:if (nextProps.isLoaded) 然后执行this.setState((prevState) =&gt; ({ idx: prevState.idx + 1 }));但是为什么你不能只将这个 idx 保存在 Redux 存储本身中并将其用作组件中的道具?你正在尝试做一些棘手的事情:)
    • 因为我要显示不同的视图取决于 idx 是否是最后一个。如果我将索引移动到 redux 中。我需要将所有内容都移到 redux 中。我只是好奇有没有什么好的方法来处理这个问题,只需要做出反应而不是把所有东西都放到 redux 中。
    • 我认为componentDidUpdate 是在道具更改上引入副作用的更合适的地方。如果您阅读 [reactjs.org/docs/…,您会发现它的使用并不受到高度鼓励,您应该寻找更简单的解决方案。使用componentDidUpdate,您可以访问之前的状态和道具。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多