我一直在学习一个关于更新值的教程,它是用户单击按钮时的值increments
。
但是,我有JSON
对象值要更新。当用户单击按钮和vice versa
时,应更新该值。在我尝试实现以下示例之后,它没有改变。这是我的代码:
1.点击:
<div>
Point: {item.point} 
<button onClick={() => setCount(item.point + 1)} class="btn"><i class="fa fa-arrow-up"></i></button>
<button onClick={() => setCount(item.point - 1)} class="btn"><i class="fa fa-arrow-down"></i></button>
</div>
2.使用状态:
const [count, setCount] = useState(0);
3.comments.json:
{
"id": "fa1ca3c1-cc1e-4ed9-86b8-f60d8312d499",
"author": "Neal Topham",
"avatar": "http://lorempixel.com/100/100/people/1/",
"date": "2017-02-08T00:30:05.552Z",
"message": "Mungkin ada fenomena paranormal yang tidak bisa dijelaskan. Lebih baik nyala mati sendiri daripada tidak nyala sama sekali",
"point": 3,
}
4.教程链接:
https://reactjs.org/docs/hooks-state.html
在您的情况下,您可能需要您的对象来生活在您的状态中。
使用状态
const [message, setMessage] = useState({
"id": "fa1ca3c1-cc1e-4ed9-86b8-f60d8312d499",
"author": "Neal Topham",
"avatar": "http://lorempixel.com/100/100/people/1/",
"date": "2017-02-08T00:30:05.552Z",
"message": "Mungkin ada fenomena paranormal ...",
"point": 3,
});
你不能改变状态的一部分,所以你基本上会对它进行修改
const addCount = (n) => {
setMessage({
...message,
point: message.point + n
});
};
<div>
Point: {message.point} 
<button onClick={() => addCount(1)} class="btn"><i class="fa fa-arrow-up"></i></button>
<button onClick={() => addCount(-1)} class="btn"><i class="fa fa-arrow-down"></i></button>
</div>
1。使用状态:
const [items, setItems] = useState([]);
2.修改按钮:
<button
onClick={() => {
// first, clone it
const newItems = [...items];
newItems[idx] = {
...item,
point: item.point + 1
};
setItems(newItems);
}}
className="btn-upvote"
>
<i className="fa fa-arrow-up"></i>
</button>
<button
onClick={() => {
// first, clone it
const newItems = [...items];
newItems[idx] = {
...item,
point: item.point - 1
};
setItems(newItems);
}}
className="btn-downvote"
>
<i className="fa fa-arrow-down"></i>
</button>
使用count
而不是item.point
。
const [count, setCount] = useState(item.point);
<div>
Point: {count} 
<button onClick={() => setCount(item.point + 1)} class="btn"><i class="fa fa-arrow-up"></i></button>
<button onClick={() => setCount(item.point - 1)} class="btn"><i class="fa fa-arrow-down"></i></button>
</div>
问题是在渲染item.point
时,onClick侦听器会更新count
变量。
此时,React只是呈现item
对象的point
属性,该属性不与count
状态变量的任何更改绑定。
根据您的应用程序逻辑,您可能希望将item.point
直接提取到count
变量中,如下所示:
const [count, setCount] = useState(item.point);
并渲染{count}
而不是{item.point}
然而,这种方法只能在一个方向上工作,这意味着当您单击按钮时,渲染值将发生变化,但不会更新item
对象的实际point
属性