React.js通过键和值过滤状态 [英] Reactjs filter state by key and value
问题描述
在这里与新手联系.
我正在尝试匹配位于我的州的特定ID的值,因此我可以在通过api更新数据库之前更改一些值.
I'm trying to match the value of a specific id located in my state, so I can change some value before updating the database via my api.
状态为
state = {
library: []
}
,然后在axios更改状态时,数组看起来像这样:
and then with when the axios changes the state the array looks something like:
0:{_id:"", time:"", value:""},
2:{_id:"", time:"", value:""}
当我运行console.log时,它是这样读取的.
When I run console.log, it reads it like this.
(2) [{…}, {…}]0: {_id: "5c82803ad634ea0bebfb3eff", time: "2019-03-08T14:46:18.663Z", value:""}1: {_id: "5c827fb9d634ea0bebfb3efe", time: "2019-03-08T14:44:09.818Z", value:""}
因此,基本上,当我输入由_id标识的特定输入字段时,我需要更新该特定状态的值状态.
So basically when I type in a specific input field, identified by it's _id, I need to update the value state of that specific state.
这是我到目前为止编写的代码._id是输入字段的唯一键和我输入的事件值.
Here's the code I have written so far. _id is the unique key of the input field and event value what I'm typing.
updateRead = (_id, event) => {
console.log(_id);
console.log(event.target.value)
this.setState(?????)
};
我们将不胜感激!
欢呼
推荐答案
You can use the array map
method on the library
array in your state, and just return the elements as is if the _id
doesn't match, and update the value
if the _id
does match.
updateRead = (_id, event) => {
const { value } = event.target;
this.setState(prevState => ({
library: prevState.library.map(read => {
if (read._id !== _id) {
return read;
}
return {
...read,
value
};
})
}));
};
这篇关于React.js通过键和值过滤状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!