reactjs - 如果父状态值发生变化,如何更新子组件

标签 reactjs react-native

我有一个仪表板,我在其中使用搜索字段过滤数据。在更改状态数据时,我想重新加载图形组件,其中我已将状态属性作为数据值传递。

const intialState = {
    graphData:  null,
    costCenterList: [],
    costCenterValue: []
};
class Dashboard extends Component {
  constructor(props){
    super(props);
    this.state = intialState;
    this.handleCostCenterChange = this.handleCostCenterChange.bind(this);
  }
  handleCostCenterChange(event, values){     
    var filtered = this.state.graphData.filter(el => values.includes(el.costCode));
    this.setState({graphData: filtered});
  }

  render() { 
    <Grid item md={2}>
        <div>
          <InputLabel id="costCenterLabel" style= {{textAlign:'left', fontWeight:'bold'}}>Cost Center</InputLabel>
           <FormControl style={{minWidth:'200px', width:'100%'}} variant="outlined" >
              <Autocomplete
                  multiple
                  options={this.state.costCenterList.map((p) => p)}
                  renderInput={params => (
                    <TextField {...params} margin="normal" variant="outlined" fullWidth autoComplete="off" />
                  )}
                  onChange={this.handleCostCenterChange}
              />
           </FormControl>
        </div>
      </Grid>

      <Grid item md={12}>
        <BarGraph graphData={this.state.graphData}/>
      </Grid>
  }

 }

条形图代码如下:

export default class BarGraph extends Component {
  state = {
    dataForChart: {
      datasets: [
      ]
    }
  }

  render() {
    return (
      <div>
        <h3>Hours Per Cost Center</h3>
        <Bar ref="chart" data={this.state.dataForChart} options = {this.state.barChartOptions} height={242} width={486}/>
      </div>
    );
  }


  componentDidMount() {
    try {

      let graphData = this.props.graphData;
      let newState = Object.assign({}, this.state);

      newState.dataForChart.datasets =[{barPercentage: 1, label:'Hours Per Cost Center ', data : graphData, backgroundColor : oBarColours, borderWidth:2, borderColor:oBarColours}];
      newState.dataForChart.labels = oCostCenterDistinct;

      this.setState(newState);
      } catch (error) {
      console.log("Network error: " + error);
    }
  }

}

我想根据状态的 graphData 变化更新组件。在使用 this.setState 进行更改时,它会更新状态值,但不会更新组件的新数据。

任何人都可以帮助我在这里缺少什么吗?

最佳答案

需要响应 Prop 更新。将数据处理分解为一个实用函数,该函数在组件安装时调用,并在更新到 props 时再次调用。

export default class BarGraph extends Component {
  state = {
    dataForChart: {
      datasets: []
    }
  };

  setData() {
    try {
      const { graphData } = this.props;
      const newState = { ...this.state };

      newState.dataForChart.datasets = [
        {
          barPercentage: 1,
          label: "Hours Per Cost Center ",
          data: graphData,
          backgroundColor: oBarColours,
          borderWidth: 2,
          borderColor: oBarColours
        }
      ];
      newState.dataForChart.labels = oCostCenterDistinct;

      this.setState(newState);
    } catch (error) {
      console.log("Network error: " + error);
    }
  }

  componentDidMount() {
    this.setData();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.graphData !== this.props.graphData) {
      this.setData();
    }
  }

  render() {
    return (
      <div>
        <h3>Hours Per Cost Center</h3>
        <Bar
          ref="chart"
          data={this.state.dataForChart}
          options={this.state.barChartOptions}
          height={242}
          width={486}
        />
      </div>
    );
  }
}

关于reactjs - 如果父状态值发生变化,如何更新子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59765441/

相关文章:

javascript - ReactJS传递多个元素

javascript - Onclick不显示表单 react

css - 如何在 Enzyme 中测试 CSS 悬停 - React

react-native - 我尝试了 React Native Tab View。路由导航在 renderScene 组件中不起作用

android-studio - React-native (Signed) release apk 在设备中不断崩溃

javascript - 替换可观察数据时的 MobX 性能

javascript - Redux 表单字段级验证在 Edge 中不起作用

android - react native 博览会 : Network error on android

react-native - react 导航 (V2) : How to set the Icon and the label of a stack Navigator inside a Drawer Navigator?

reactjs - 改变安卓:usesCleartextTraffic to false