首页 > 解决方案 > 如何在 React 中聚合子组件状态的值?

问题描述

我有一个Parent组件和许多Child组件,每个组件value在安装时都从 API 加载异步。我想在Parent组件中显示这些值的总和。在 React 中执行此操作的最佳模式是什么?

export class Parent extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
     <>
      <Child name='nick' />
      <Child name='lucile' />
      <Child name='buster' />
      <span>{ TBD: Total of each Child's state.value ??? }</span>
     </>
    )
  }
export class Child extends React.Component {

  constructor(props) {
    super(props);
    this.state = { value: 0 }
  }

  async componentDidMount(){
    let response = await axios.get(`https://getvaluefromapi/{this.props.name}`)
    this.setState({value: response.data.value})
  }

  render() {
    return (<span>{this.state.value}<span>)
  }
}

标签: javascriptreactjs

解决方案


import React from "react";
import Child from "../components/child";

class Parent extends React.Component {
  //State
  state = {};

  getValue = (user, value) => {
    this.setState({ [user]: value });
  };

  render() {
    return (
      <div>
        <Child name="nick" getValue={this.getValue} />
        <Child name="buster" getValue={this.getValue} />
        <Child name="lucile" getValue={this.getValue} />
        <div>{this.state.nick + this.state.buster + this.state.lucile}</div>
      </div>
    );
  }
}
export default Parent;

import React, { Component } from "react";

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
    };
  }

  async componentDidMount() {
    let response = await axios.get(`https://getvaluefromapi/{this.props.name}`);
    this.setState({ value: response.data.value });
    this.props.getValue(this.props.name, response.data.value);
  }

  render() {
    return <p>{this.state.value}</p>;
  }
}
export default Child;

您想如何从这里继续,完全是您的选择。您可以在 componentDidUpdate() 中将它们全部添加到总值中。或者你直接在 dom 中显示它们。

您还可以直接从父元素传递一个函数,该函数会将当前的 totalValue 与每个独立值相加,但是,由于子元素的排序和同时呈现,我不知道这是否可行。如果所有孩子同时渲染,您可能会在总值中得到错误的值。但是,我认为这就是该选项的样子。

import React from "react";
import Child from "../components/child";

class Parent extends React.Component {
  //State
  state = {
    totalValue: 0,
  };

  getValue = (value) => {
    this.setState({ totalValue: this.state.totalValue + value });
  };

  render() {
    return (
      <div>
        <Child name="nick" getValue={this.getValue} />
        <Child name="buster" getValue={this.getValue} />
        <Child name="lucile" getValue={this.getValue} />
        <div>{this.state.totalValue}</div>
      </div>
    );
  }
}
export default Parent; 

import React, { Component } from "react";

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
    };
  }

  async componentDidMount() {
    let response = await axios.get(`https://getvaluefromapi/{this.props.name}`);
    this.setState({ value: response.data.value });
    this.props.getValue(response.data.value);
  }

  render() {
    return <p>{this.state.value}</p>;
  }
}
export default Child;

推荐阅读