React.js中的setState与replaceState

JavaScript

猪猪Stafan小卤蛋

2020-03-12

我是React.js库的新手,我正在浏览一些教程,发现了:

  • this.setState
  • this.replaceState

给出的说明不是很清楚(IMO)。

setState is done to 'set' the state of a value, even if its already set 
in the 'getInitialState' function.

同样,

The replaceState() method is for when you want to clear out the values 
already in state, and add new ones.

我先尝试this.setState({data: someArray});然后this.replaceState({test: someArray});再进行console.logging它们,发现state现在同时具有datatest

然后,我this.setState({data: someArray});依次尝试this.setState({test: someArray});,然后进行console.logging它们,发现它们state又具有datatest

那么,两者之间到底有什么区别?

第1130篇《React.js中的setState与replaceState》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
小宇宙Itachi 2020.03.12

由于replaceState现已弃用,因此这是一个非常简单的解决方法。尽管您很少/应该诉诸于此。

删除状态:

for (const old_key of Object.keys(this.state))
    this.setState({ [old_key]: undefined });

或者,如果您不想多次拨打 setState

const new_state = {};
for (const old_key of Object.keys(this.state))
    new_state[old_key] = undefined;
this.setState(new_state);

本质上,该状态下的所有先前键现在都返回undefined,可以很容易地用一条if语句过滤掉

if (this.state.some_old_key) {
    // work with key
} else {
    // key is undefined (has been removed)
}

if ( ! this.state.some_old_key) {
    // key is undefined (has been removed)
} else {
    // work with key
}

在JSX中:

render() {
    return <div>
        { this.state.some_old_key ? "The state remains" : "The state is gone" }
    </div>
}

最后,要“替换”状态,只需将新状态对象与旧状态副本合并为undefined,然后将其设置为state即可:

const new_state = {new_key1: "value1", new_key2: "value2"};
const state = this.state;

for (const old_key of Object.keys(state))
    state[old_key] = undefined;

for (const new_key of Object.keys(new_state))
    state[new_key] = new_state[new_key];

this.setState(state);
小小Pro 2020.03.12

根据docsreplaceState可能会被弃用:

此方法在扩展React.Component的ES6类组件上不可用。在以后的React版本中可能会完全删除它。

小胖Sam 2020.03.12

setState当前和以前的状态合并。使用replaceState,它将抛出当前状态,并仅用您提供的状态替换它。通常setState使用该命令,除非出于某种原因确实需要删除密钥;但是将它们设置为false / null通常是更明确的策略。

虽然有可能改变。replaceState当前使用传递的对象作为状态,即replaceState(x),一旦被设置this.state === x它比轻一些setState,因此如果成千上万的组件频繁设置其状态,则可以将其用作优化。
我用这个测试用例断言了这一点


如果您的当前状态是{a: 1},并且您打电话this.setState({b: 2}); 当应用状态时,它将为{a: 1, b: 2}如果你打电话,this.replaceState({b: 2})你的状态将是{b: 2}

旁注:状态不是立即设置的,因此this.setState({b: 1}); console.log(this.state)在测试时不要这样做

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android