如果我有一个像这样的对象数组
[{name: 'james', name: 'john'}]
,我知道john的索引,并且想要更改john的值。
person = person.map((p, i)=>i===index?({...p, name: 'changed john'})):p)
this.setState({person})
但是如果数组像这样怎么办?
['james', 'john']
答案 0 :(得分:1)
但是如果数组像这样怎么办? ['james','john']
由于更新状态的正确方法是使用 [oslo_messaging]
topic = octavia_prov
# Topic for octavia's events sent to a queue
event_stream_topic = neutron_lbaas_event
方法,因此,像setState
这样直接改变状态的行为将不起作用。我认为我们照常使用this.state.list[i]="Changed John"
。像这样:
Array.prototype.map()
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'));
答案 1 :(得分:0)
您想要这样的东西吗?
person = person.map((p, i) => p === "john" ? "changed john" : p);
答案 2 :(得分:0)
这很容易。这里有两种情况的示例:
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])
我建议访问 MDN docs,以探索其他(所有)示例。
答案 3 :(得分:0)
person = person.map((p,i)=> p ===“ john”?“ changed john”:p);