如何在React.js中动态更新状态?

时间:2020-10-15 06:45:52

标签: javascript node.js reactjs

我想在每次选择用户时动态更新状态 CurrentIndex 。现在,我将其硬编码为0。我想更改它。

当我单击用户列表时,我想更新currentIndex。
SidePanel包含用户及其输出的名字,姓氏

的数组
class Home extends Component {
  state = {  
    loadUsers: [],
    currentIndex: 0,
  };

  async componentDidMount() {

    const res = await axios.get("http://localhost:5000/users");
    this.setState({ loadUsers: res.data });
  }

  render() {

    return (
      <Fragment>
        <div className="row">
          <div className="col-md-3" style={{ backgroundColor: "#303F9F" }}>
            <Typography variant="h6">List all Counsellors</Typography>
            {this.state.loadUsers.map((user) => {
              const { _id, firstname, lastname } = user;
              return (
                <div key={_id}>
                  <SidePanel
                    id={_id}
                    firstname={firstname}
                    lastname={lastname}
                  />
                </div>
              );
            })}
          </div>
          <div className="col-md-4">
            {this.state.loadUsers.length > 1 && (
              <div>
                <MiddlePanel
                  user={this.state.loadUsers[this.state.currentIndex]}
                />
              </div>
            )}
          </div>
        </div>
      </Fragment>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

创建一个处理程序以使用映射的索引,并在需要时通过/附加处理程序。

class Home extends Component {
  state = {  
    loadUsers: [],
    currentIndex: 0,
  };

  ...

  incrementIndex = (currentIndex) => (e) => this.setState({ currentIndex });

  render() {

    return (
      <Fragment>
        <div className="row">
          <div className="col-md-3" style={{ backgroundColor: "#303F9F" }}>
            ...
            {this.state.loadUsers.map((user, index) => {
              const { _id, firstname, lastname } = user;
              return (
                <div key={_id}>
                  <SidePanel
                    id={_id}
                    firstname={firstname}
                    lastname={lastname}
                    onClick={incrementIndex(index)} // <-- pass handler to Panel
                  />
                </div>
              );
            })}
          </div>
          ...
        </div>
      </Fragment>
    );
  }
}