我想在状态数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
我担心用push修改数组可能会导致麻烦——它安全吗?
另一种方法是复制数组,setstate看起来很浪费。
我想在状态数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
我担心用push修改数组可能会导致麻烦——它安全吗?
另一种方法是复制数组,setstate看起来很浪费。
当前回答
当我想修改数组状态时,我也遇到了类似的问题 同时保留元素在数组中的位置
这是一个在like和different之间切换的函数:
const liker = (index) =>
setData((prevState) => {
prevState[index].like = !prevState[index].like;
return [...prevState];
});
正如我们所说,函数接受数组状态元素的索引,然后我们继续修改旧状态并重建状态树
其他回答
目前很多人都面临着更新useState钩子状态的问题。我使用这种方法来安全地更新它,并想在这里分享它。
这就是我的状态
const [state, setState] = useState([])
假设我有一个对象名为obj1,我想把它附加到我的状态中。我建议这样做
setState(prevState => [...prevState, obj1])
这将安全地在末尾插入对象,并保持状态一致性
这对我来说很有用,可以在数组中添加一个数组
this.setState(prevState => ({
component: prevState.component.concat(new Array(['new', 'new']))
}));
下面是一个2020年的Reactjs Hook示例,我认为它可以帮助其他人。我用它来添加新的行到一个Reactjs表。如果有需要改进的地方,请告诉我。
向功能状态组件添加新元素:
定义状态数据:
const [data, setData] = useState([
{ id: 1, name: 'John', age: 16 },
{ id: 2, name: 'Jane', age: 22 },
{ id: 3, name: 'Josh', age: 21 }
]);
有一个按钮触发一个函数来添加一个新元素
<Button
// pass the current state data to the handleAdd function so we can append to it.
onClick={() => handleAdd(data)}>
Add a row
</Button>
function handleAdd(currentData) {
// return last data array element
let lastDataObject = currentTableData[currentTableData.length - 1]
// assign last elements ID to a variable.
let lastID = Object.values(lastDataObject)[0]
// build a new element with a new ID based off the last element in the array
let newDataElement = {
id: lastID + 1,
name: 'Jill',
age: 55,
}
// build a new state object
const newStateData = [...currentData, newDataElement ]
// update the state
setData(newStateData);
// print newly updated state
for (const element of newStateData) {
console.log('New Data: ' + Object.values(element).join(', '))
}
}
this.setState(preState=>({arrayvar:[...prevState.arrayvar,newelement]}))
这个方法可以解决这个问题。
React可以批处理更新,因此正确的方法是为setState提供一个执行更新的函数。
对于React更新插件,以下将可靠地工作:
this.setState( state => update(state, {array: {$push: [4]}}) );
或者对于concat():
this.setState( state => ({
array: state.array.concat([4])
}));
下面以https://jsbin.com/mofekakuqi/7/edit?js,output为例说明如果您弄错了会发生什么。
setTimeout()调用正确地添加了三个项,因为React不会在setTimeout回调中批量更新(参见https://groups.google.com/d/msg/reactjs/G6pljvpTGX0/0ihYw2zK9dEJ)。
错误onClick只会添加“第三”,但固定的一个,将添加F, S和T如预期。
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
array: []
}
setTimeout(this.addSome, 500);
}
addSome = () => {
this.setState(
update(this.state, {array: {$push: ["First"]}}));
this.setState(
update(this.state, {array: {$push: ["Second"]}}));
this.setState(
update(this.state, {array: {$push: ["Third"]}}));
};
addSomeFixed = () => {
this.setState( state =>
update(state, {array: {$push: ["F"]}}));
this.setState( state =>
update(state, {array: {$push: ["S"]}}));
this.setState( state =>
update(state, {array: {$push: ["T"]}}));
};
render() {
const list = this.state.array.map((item, i) => {
return <li key={i}>{item}</li>
});
console.log(this.state);
return (
<div className='list'>
<button onClick={this.addSome}>add three</button>
<button onClick={this.addSomeFixed}>add three (fixed)</button>
<ul>
{list}
</ul>
</div>
);
}
};
ReactDOM.render(<List />, document.getElementById('app'));