简体   繁体   中英

How to dynamically update state in React.js?

I want to dynamically update state CurrentIndex whenever I select a user.Right now I am hardcoding it to 0. I want to change that.

I want to update currentIndex whenever I click on the list of users.
SidePanel contains arrays of user and its outputting firstname,lastname

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

Create a handler to consume the mapped index and pass/attach handler where you need it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM