【问题标题】:Using setState() for update view with data from API - ReactJS使用 setState() 使用来自 API 的数据更新视图 - ReactJS
【发布时间】:2019-04-02 01:21:09
【问题描述】:

我是 ReactJS 的新手。在我当前的项目中,我正在将数据从 Mongo 数据库填充到 HTML 表中,并且我有一列带有复选框(根据 db 值动态创建)用于选择默认配置文件(见下图)。检查一个配置文件时,数据库中的特定配置文件将更新为 true 标志,而其他配置文件为 false

在复选框上单击它将调用 API 来更新 db 标志。更新数据库后,我需要调用一个 API 从同一个集合和更新表中获取数据。我正在使用以下代码。

我正在尝试使用 setState 来呈现新数据而不刷新页面。我想我在没有更好理解的情况下使用 setState,我需要澄清这一点。我的问题是下面的代码有什么问题,除了使用 setState 之外还有什么更好的方法来实现这种情况?

Profiles.jsx - 渲染()

render() {
return (
  <React.Fragment>
    <div>
      <table className="table">
        <thead className="thead-dark">
          <tr>
            <th scope="col">ID</th>
            <th scope="col">Create Date</th>
            <th scope="col">Last Updated Date</th>
            <th scope="col">Default Profile</th>
            <th scope="col">Update</th>
            <th scope="col">Delete</th>
          </tr>
        </thead>
        <tbody>
          {this.state.profilesData.map(prof => (
            <tr key={prof._id}>
              <th scope="row">{prof._id}</th>
              <td>{prof.createdDate}</td>
              <td>{prof.lastUpdatedDate}</td>
              <td align="center">
                {prof.defaultProfile === true ? (
                  <input
                    name="defaultProfileCheck"
                    type="checkbox"
                    aria-label="Checkbox for following text input"
                    onChange={() => this.toggleDefault(prof._id)}
                    defaultChecked
                  />
                ) : (
                  <input
                    name="defaultProfileCheck"
                    type="checkbox"
                    aria-label="Checkbox for following text input"
                    onChange={() => this.toggleDefault(prof._id)}
                  />
                )}
              </td>
              <td>
                <button type="button" className="btn btn-warning">
                  Update
                </button>
              </td>
              <td>
                <button type="button" className="btn btn-danger">
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </React.Fragment>
);

}

toggleDefault - onChange

state = {
  profilesData: []
};

async componentDidMount() {
const profiles = await getUserProfiles();  //Service Call
this.setState({ profilesData: profiles.data }); }

async toggleDefault(_id) {
if (window.confirm("Are you sure?")) {
  try {
    await setDefaultProfile(_id); //Service Call
  } catch (ex) {
    if (ex.response && ex.response.status === 404) toast.error(ex.message);
  }
  //toast.success("Done.");
  const profiles = await getUserProfiles(); //Service call for get updated data
  this.setState({ profilesData: profiles.data }); //Trying to setState for update view
} else {

}
}

谢谢。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这正是 ComponentDidUpdate 的用例。

    请到这里:https://reactjs.org/docs/react-component.html#componentdidupdate 我在下面提供了一个示例,它可以帮助您按照自己的意愿更新数据。

    componentDidUpdate(prevProps, prevState, snapshot)
    
    componentDidUpdate(prevProps) {
      // Typical usage (don't forget to compare props):
      if (this.props.userID !== prevProps.userID) {
        this.fetchData(this.props.userID);
      }
    }
    

    【讨论】:

    • 非常感谢..您的回答帮助我解决了我的问题。正如你所说,我使用componentDidUpdate()并将“defaultChecked”更改为checked = {prof.defaultProfile}。再次感谢您。
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 2014-01-16
    • 2021-05-04
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多