我们如何在分派动作时也修改组件状态?

How can we modify component state as well when an action is dispatched?

`

import React, {Component} from 'react';
import {connect} from 'react-redux';
import Chart from '../components/chart.js';
import GoogleMap from '../containers/googlemap';
import {removeCityMap} from '../actions/index';
import { bindActionCreators } from "redux";
import AttributeSelector from './attributeselector'

class WeatherBoard extends Component{
    constructor(props){
        super(props);
        this.state = {
            chartData1: []
        }
    }
    weatherAttrMapper(attrName){
        //Setting the state which is based on the data received from action dispatched.
        this.setState({
            chartData1:this.props.weather[0].list.map(weather => weather.main[attrName])
        })
    }
    renderMapList(cityData){
        //Based on the weather prop received when action is dispached I want to set the state before rendering my <chart> element.
        this.weatherAttrMapper('temp');
        return(
            <tr key = {cityName}>
                <td><Chart data = {this.state.chartData1} color = "red" units="K"/></td>
            </tr>
        )
    }
    render(){
        return(
            <table className="table table-hover">
                <tbody>
                    {this.props.weather.map(this.renderMapList.bind(this))} 
                </tbody>
            </table>
        )
    }
}
//This is the weather state coming from my reducer which is being used here.
function mapStateToProps({ weather }) {
    return { weather };
}
function mapDispatchToProps(dispatch) {
    return bindActionCreators({ removeCityMap }, dispatch);
}
  
export default connect(mapStateToProps,mapDispatchToProps)(WeatherBoard);

`我对状态管理有疑问。

问题陈述:我有一个容器 abc.JS 文件,它通过 mapStateToProps 映射到 redux 状态。 我有一个按钮单击操作处理程序,它从 API 获取数据。当我的 actionhandler 被调度时,它会在 abc.js 中命中我的渲染方法。现在我的问题是我也在 abc.js 中维护状态,它也在 render 方法中使用,这需要在调度动作时修改。那么我如何设置我的 abc.js 状态,它也可以被渲染。

我还添加了 abc.js 的确切代码片段。所以基本上我在调度动作时进入我的渲染方法,我在这里我需要以某种方式设置状态。

谢谢。

理想情况下,如果您依赖于使用道具设置的状态值。使用 componentWillReceiveProps 生命周期钩子来设置状态。它会完成工作。只要更新阶段的道具发生变化,它就会被触发

这取决于你需要做什么,如果你只需要调度一个动作并设置状态 "at the same time" 那么这样的事情就可以了:

...
  handleOnClick = () => {
    this.props.actions.myAction();
    this.setState({ myStateField: "myNewValue" });
  }

  render() {
    return (
      <div>
        <h1>MyContainer</h1>
        <button onClick={this.handleOnClick}>Click me</button>
      </div>
    );
  }

如果您需要分派一个动作,那么根据管理器中状态的更新方式,您还需要更新状态,然后您可以使用像 componentWillReceiveProps 这样的简单生命周期方法,在那里您可以阅读新的道具,甚至将其与旧道具进行比较并对其采取行动,这意味着您可以在此基础上更新您的状态。让我知道这是否有帮助,否则我可以更新我的答案;)

编辑:

阅读您的评论后,这就是您想要做的:

...
componentWillReceiveProps(nextProps) {
  // In here you can also use this.props to compare the current props
  // to the new ones and do something about it
  this.setState({ myStateField: nextProps.propFromRedux });
}
...

在调度您的操作之前,您可以只说 this.setState{},它会修改您的组件状态,一旦操作再次调度它,就会导致重新渲染,因为此操作可能会更改商店的某些状态。