我想在点击将数据库中标记的值从false更新为true的按钮后,更改标记状态变量为true的消息的颜色。
但当我点击一条消息时,所有消息的颜色都从蓝色变为绿色。我只想更改信息的颜色
解决方案是什么?
const [markState, setMarkState] = useState(false);
const markonclickHandler = async (id) => {
const dataRaw = await fetch(`${baseUrl}/contactformunreadmessage/${id}`, {
method: "PUT",
headers: {
"content-type": "application/json",
authToken: authToken,
},
body: JSON.stringify({ mark: true }),
});
const data = await dataRaw.json();
setMarkState(data.success);
在jsx 中
<div className="p-8 flex flex-wrap font-mono">
{readMessages.map((message) => {
return (
</div>
{markState ? (
<button
className=" font-serif text-green-600 cursor-pointer text-right"
>
marked as read
</button>
) : (
<button
onClick={() => markonclickHandler(message._id)}
className=" font-serif text-blue-600 cursor-pointer text-right"
>
mark as read
</button>
)}
</div>
</div>
假设整个readMessages
列表只有一个markState
变量,则更改markState
将修改所有子项的按钮选择。
简单地说,您需要为readMessages
数组的每个子级维护markState
。
例如:
const Message = ({ message }) => {
const [markState, setMarkState] = useState(false)
// your markonclickHandler can live here as such
// but I highly recommend you to move it to a some state management tool
const markonclickHandler = async (id) => {
const dataRaw = await fetch(`${baseUrl}/contactformunreadmessage/${id}`, {
method: "PUT",
headers: {
"content-type": "application/json",
authToken: authToken,
},
body: JSON.stringify({ mark: true }),
})
const data = await dataRaw.json()
setMarkState(data.success)
}
return (
<div>
{markState ? (
<button className=" font-serif text-green-600 cursor-pointer text-right">
marked as read
</button>
) : (
<button
onClick={() => markonclickHandler(message._id)}
className=" font-serif text-blue-600 cursor-pointer text-right"
>
mark as read
</button>
)}
</div>
)
}
<div className="p-8 flex flex-wrap font-mono">
{readMessages.map((message) => {
return <Message message={message} key={message._id} />
})}
</div>