gpt4 book ai didi

javascript - 将空数组插入 react 的状态

转载 作者:行者123 更新时间:2023-11-29 21:08:54 26 4
gpt4 key购买 nike

http://jsbin.com/zehoceloka/1/edit

我的输入数字是动态的,它取决于 API 它有多少数据。所以首先我将它映射到 View 。但还有一个功能,用户可以添加新项目。我试图推送一个新的空数组,但没有任何反应。我做错了吗?

class HelloWorldComponent extends React.Component {

constructor(){
super()
this.addNewRow = this.addNewRow.bind(this);
this.state = {
"rules":[
"age must be above 10",
"must wear shoe"
]
}
}

addNewRow(e){
const updated = this.state.rules.push("");
this.setState({rules:updated});
}


render() {
return (
<div>
{this.state.rules.map(obj =>
<input type="text" defaultValue={obj} />
)}
<button>Add New Rules</button>
<br /><br />
<pre>{JSON.stringify(this.state.rules,null,2)}</pre>
</div>
);
}
}

最佳答案

你忘了定义按钮的点击事件,使用这个:

<button onClick={this.addNewRow}>Add New Rules</button>

这一行中的几个问题:

const updated = this.state.rules.push("");

1.切勿直接通过 this.state.a.push()this.state.a = '' 改变状态变量>,始终使用 setState 来更新值。

2.a.push() 不会返回更新后的数组,它会返回插入数组的值。

来自 Doc :

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

检查此工作代码:

class HelloWorldComponent extends React.Component {

constructor(){
super()
this.addNewRow = this.addNewRow.bind(this);
this.state = {
rules:[
"age must be above 10",
"must wear shoe"
]
}
}

addNewRow(e){
let updated = this.state.rules.slice();
updated.push("");
this.setState({rules:updated});
}


render() {
return (
<div>
{this.state.rules.map(obj =>
<input type="text" defaultValue={obj} />
)}
<button onClick={this.addNewRow}>Add New Rules</button>
<br /><br />
<pre>{JSON.stringify(this.state.rules,null,2)}</pre>
</div>
);
}
}

ReactDOM.render(
<HelloWorldComponent />,
document.getElementById('react_example')
);
<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='react_example'/>

关于javascript - 将空数组插入 react 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42666254/

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