当操作被调度时,我们如何修改组件状态?

问题描述 投票:0回答:3

`

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 获取数据。当我的动作处理程序被调度时,它会命中 abc.js 中的渲染方法。现在我的要求是我也在 abc.js 中维护状态,该状态也在渲染方法中使用,并且在分派操作时需要对其进行修改。那么我如何设置我的 abc.js 状态也可以渲染。

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

谢谢。

reactjs redux
3个回答
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
这样的简单生命周期方法,您可以在那里读取新的道具,甚至进行比较到旧的 props 并对其采取行动,这意味着您可以在此基础上更新您的状态。让我知道这是否有帮助,否则我可以更新我的答案;)

编辑:

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

...
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 });
}
...

0
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.