简体   繁体   中英

update array without object using map

if I have an array of object like this

[{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})

but what if the array is like this? ['james', 'john']

but what if the array is like this? ['james', 'john']

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>


你想要这样的东西吗?

 person = person.map((p, i) => p === "john" ? "changed john" : p);

It's pretty easy. Here you have examples for both situations:

 const test = [{name: 'james', name: 'john'}]; // Here we're accessing the 1st element and its 'name' property console.log(test[0].name);

 // Here we're accessing the 2nd element. // JavaScript arrays are zero-indexed: the first element of an array is at index 0 const test2 = ['james', 'john']; console.log(test2[1])

I suggest visiting MDN docs for exploring other (all) examples.

person = person.map((p, i) => p === "john" ? "changed john" : p);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM