我在 React.js 中尝试了这个正确修改状态数组
Correct modification of state arrays in React.js
任何元素都没有添加到数组中。
[...array,[{},{}]] 和
this.state.aaaa.concat[newArray] 对我的代码无效。 我想将一个 JSON 数组设置为一个状态,但它不起作用。
const setCountries = COUNTRIES.map((country) => {
console.log("OMG!");
return {
id: country,
text: country,
};
});
class Stack extends Component {
constructor(props) {
super(props);
this.state = {
testarray: [],
};
this.setState( {testarray: setCountries});
console.log("MO"+JSON.stringify(setCountries))
console.log("UU"+JSON.stringify(this.state.testarray))
控制台说。莫
MO[{"id":"Afghanistan","text":"Afghanistan"},{"id":"Albania","text":"Albania"},{"id":"Algeria","text":"Algeria"},{"id":"Andorra","text":"Andorra"},{"id":"Angola","text":"Angola"},{"id":"Anguilla","text":"Anguilla"},{"id":"Antigua & Barbuda","text":"Antigua & Barbuda"},{"id":"Argentina","text":"Argentina"},{"id":"Armenia","text":"Armenia"},{"id":"Aruba","text":"Aruba"},{"id":"Australia","text":"Australia"},{"id":"Austria","text":"Austria"},{"id":"Azerbaijan","text":"Azerbaijan"},{"id":"Bahamas","text":"Bahamas"},{"id":"Bahrain","text":"Bahrain"},
UU[]
另一种方式
constructor(props) {
super(props);
this.state = {
suggestions: [{ id: "Thailand", text: "Thailand" }],
};
this.setState( {suggestions: [{ id: "India", text: "India" }] } );
this.setState( {suggestions: [...this.state.suggestions,[{ id: "India", text: "India" }]] } );
也是无效的。
结果是 UU[{"id":"Thailand","text":"Thailand"}]...印度没有设置。
答案 0 :(得分:0)
对于两个变量都作为数组,所以你需要将两者都分布在数组中
喜欢
[...prev,...new]
你的情况最好使用 setState 回调
this.setState(state => {
state.suggestions = [...state.suggestions, ...[{
id: "India",
text: "India"
}]]
return state
});
答案 1 :(得分:0)
您正在记录设置状态的正下方,实际上是异步的..
请试试这个
this.setState( {testarray: setCountries},()=>{
console.log(this.state.testarray)
});