gpt4 book ai didi

javascript - 在 native react 中更新/更改状态对象的最佳方法?

转载 作者:行者123 更新时间:2023-12-03 13:58:18 25 4
gpt4 key购买 nike

更新 State 对象深处的嵌套属性的最佳方法是什么?

// constructor --
this.state.someprop = [{quadrangle: {rectangle: {width: * }}, ...}]
...

我想更新矩形对象的宽度。

this.state.quadrangle.rectangle.width = newvalue // isn't working

我可以让它像这样工作:

const {quadrangle} = this.state
quadrangle.rectangle.width = newvalue
this.setState = {
quadrangle: quadrangle
}

但是这种方法听起来并不是性能/内存的最佳方法

最佳答案

// ES6 WAYS TO UPDATE STATE
// NOTE: you MUST use this.setState() function for updates to your state
class Example extends Component {

constructor(props) {
super(props);
this.state = {
name: 'John',
details: {
age: 28,
height: 1.79,
}
}

componentDidMount() {
this.handleChangeName('Snow');
this.handleAgeChange(30);
}

componentDidUpdate() {
console.log(this.state);
/*
returns
{
name: 'Snow',
details: {
age: 30,
height: 1.79,
}
}
*/
}

// this way you keep your previous state immutable (best practice) with
// param "prevState"
handleChangeName = (_name) => {
this.setState(
(prevState) => ({
name: _name
})
)
}

//this is how you update just one property from an internal object
handleAgeChange = (_age) => {
this.setState(
(prevState) => ({
details: Object.assign({}, prevState.details, {
age: _age
})
})
)
}

// this is the simplest way to set state
handleSimpleAgeChange = (_age) => {
this.setState({
details: Object.assign({}, this.state.details, { age: _age })
})
}

render() {
return (
<h1>My name is {this.state.name} and I'm {this.state.details.age} years old</h1>
)
}

}

如果您想保持最佳实践而不使其变得更加困难,您可以这样做:

updateState = (obj) => {
if (obj instance of Object) {
this.setState(
(prevState) => (Object.assign({}, prevState, obj))
);
}
}

用法:

//code ... code ... code ...

handleAgeChange = (_age) => {
this.updateState({
details: Object.assign({}, this.state.details, { age: _age }
})
}

关于javascript - 在 native react 中更新/更改状态对象的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41100901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com