如何使状态只在react中map函数内的一个div中工作



我想在点击将数据库中标记的值从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>

相关内容

  • 没有找到相关文章

最新更新