本文介绍了如何从Reactjs组件的状态对象中删除属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个在状态下设置了属性的react组件:
If I have a react component that had a property set on it's state:
onClick() {
this.setState({ foo: 'bar' });
}
是否可以从Object.keys(this.state)
中删除"foo"
?
replaceState 方法看起来像是显而易见的方法但此后就被贬值了.
The replaceState method looks like the obvious method to try but it's since been depreciated.
推荐答案
您可以将foo
设置为undefined
,就像这样
You can set foo
to undefined
, like so
var Hello = React.createClass({
getInitialState: function () {
return {
foo: 10,
bar: 10
}
},
handleClick: function () {
this.setState({ foo: undefined });
},
render: function() {
return (
<div>
<div onClick={ this.handleClick.bind(this) }>Remove foo</div>
<div>Foo { this.state.foo }</div>
<div>Bar { this.state.bar }</div>
</div>
);
}
});
更新
先前的解决方案只是从state
中删除foo
和 key
技能的值,如果您需要从state
中完全删除密钥,则可能的解决方案之一是有一个父级 key
,就像这样
The previous solution just remove value from foo
and key
skill exists in state
, if you need completely remove key from state
, one of possible solution can be setState
with one parent key
, like so
var Hello = React.createClass({
getInitialState: function () {
return {
data: {
foo: 10,
bar: 10
}
}
},
handleClick: function () {
const state = {
data: _.omit(this.state.data, 'foo')
};
this.setState(state, () => {
console.log(this.state);
});
},
render: function() {
return (
<div>
<div onClick={ this.handleClick }>Remove foo</div>
<div>Foo { this.state.data.foo }</div>
<div>Bar { this.state.data.bar }</div>
</div>
);
}
});
ReactDOM.render(<Hello />, document.getElementById('container'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
这篇关于如何从Reactjs组件的状态对象中删除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!