0

`

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 的确切代码片段。所以基本上我在调度动作时输入我的渲染方法,我在这里我需要以某种方式设置状态。

谢谢。

4

3 回答 3

0

理想情况下,如果您依赖于使用道具设置的状态值。使用 componentWillReceiveProps 生命周期挂钩 setState 。它会完成这项工作。每当更新阶段道具发生变化时都会触发它

于 2018-01-17T06:38:33.653 回答
0

这取决于您需要做什么,如果您只需要调度一个动作并“同时”设置状态,那么这样的事情会起作用:

...
  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 });
}
...
于 2018-01-17T06:38:56.903 回答
0

在调度你的动作之前,你可以说 this.setState{} 它会修改你的组件状态,一旦动作再次调度它会导致重新渲染,因为这个动作可能会改变一些商店的状态。

于 2018-01-17T06:39:07.123 回答