何时在React中保存状态是否安全? [英] When is it safe to save state in React?

查看:165
本文介绍了何时在React中保存状态是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个从表单更新状态的react组件。

Let's say I have a react component that updates state from a form.

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      someCheckboxState: false,
    }
  }
  render() {
    return (
      <input onChange={this.handleChange} checked={this.state.someCheckboxState} />
    );
  }
  handleChange(event) {
    this.setState({
      someCheckboxState: event.target.checked,
    });
  }
}

现在我想将该状态发送到服务器(或某处)。如果我这样做

Now I want to send that state to the server (or somewhere). If I just do this

handleChange(event) {
  this.setState({
    someCheckboxState: event.target.checked,
  });
  SendStateToServer(JSON.stringify(this.state)); // BAD! Not yet mutated
}

我可以把它放在 render 但是它会在初始渲染时发送到服务器以及发送状态一个名为 render 的函数似乎很愚蠢。

I could put it in render but then it will get sent to the server on initial render as well as well and it seems silly to send state a function called render.

什么时候可以坚持/序列化状态?

When is it okay to persist/serialize the state?

推荐答案

第二个React的 setState 的参数是在状态转换完成后触发的回调。

The second argument of React's setState is a callback that is fired after the state transition is complete.

this.setState(newState, () => console.log(this.state));

所以,在你的情况下:

handleChange(event) {
  this.setState({
    someCheckboxState: event.target.checked,
  }, () => {
    SendStateToServer(JSON.stringify(this.state));
  });
}

这篇关于何时在React中保存状态是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆