使用map更新没有对象的数组 [英] update array without object using map
问题描述
如果我有这样的对象数组
if I have an array of object like this
[{name:'james',name:'john'}]
我知道john的索引,想要更改john的值我会做什么
[{name: 'james', name: 'john'}]
and I know the index of john and want to change the value of john I'll do
person = person.map ((p,i)=> i === index?({... p,name:'changed john'})):p)
this.setState({person})
但如果数组是这样的呢?
['james','john']
but what if the array is like this?
['james', 'john']
推荐答案
但如果数组是这样的呢? ['james','john']
but what if the array is like this? ['james', 'john']
因为更新状态的正确方法是使用 setState
方法,因此,直接改变状态的行为如 this.state.list [i] =Changed John
将无效。我认为我们像往常一样使用 Array.prototype.map()
。像这样:
Because the correct way to update state is using setState
method, hence, the act of directly mutating state like this.state.list[i]="Changed John"
won't work. I think that we just use Array.prototype.map()
as usual. Like this:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
list: ['james', 'john']
};
}
handleDelete = i => {
const newList = this.state.list.filter((li, idx) => idx !== i);
this.setState({ list: newList });
};
handleChange = i => {
const newList = this.state.list.map(
(li, idx) => (idx === i ? 'Changed ' + li : li)
);
this.setState({ list: newList });
};
render() {
return (
<div>
{this.state.list.map((e, i) => (
<div key={i}>
<p>{e}</p>
<button onClick={() => this.handleDelete(i)}>Delete</button>
<button onClick={() => this.handleChange(i)}>Change</button>
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"><div>
这篇关于使用map更新没有对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!