gpt4 book ai didi

reactjs - 映射对象数组状态时如何重新渲染 react 组件

转载 作者:行者123 更新时间:2023-12-05 01:39:33 26 4
gpt4 key购买 nike

我正在尝试映射状态中的对象数组,有条件地从该状态返回两个 react 组件之一。然后我在某个时候更改该状态,并希望组件在其对象状态更改时重新呈现。我知道我的问题与 React 无法识别 diff 的变化有关,但我不确定为什么以及我需要更改什么模式才能使其正常工作。

这是一个代码笔: https://codepen.io/steven-harlow/pen/KKPLXRO

以及其中的代码:

const App = (props) => {
const [todos, setTodos] = React.useState([
{name: 'A', done: false},
{name: 'B', done: false},
{name: 'C', done: false},
])

React.useEffect(() => {

}, [todos])

const handleClick = (name) => {
const index = todos.find(todo => todo.name == name)
let tempTodos = todos;
tempTodos[index].done = true;
setTodos(tempTodos);
}

return (
<div>
<h1>Hello, world!</h1>
<div>
{todos.map(todo => {
return todo.done ? (<div key={'done' + todo.name}>{todo.name} : done</div>) : (<div onClick={() => handleClick(todo.name)} key={'notdone' + todo.name}>{todo.name} : not done</div>)
})}
</div>
</div>
)
}

最佳答案

给你,这个现在应该适合你了。我在其中添加了一些注释。

const App = (props) => {
const [todos, setTodos] = React.useState([
{name: 'A', done: false},
{name: 'B', done: false},
{name: 'C', done: false},
])

const handleClick = (name) => {
/*
Here you were using todos.find which was returning the object. I switched
over to todos.findIndex to give you the index in the todos array.
*/
const index = todos.findIndex(todo => todo.name === name)
/*
In your code you are just setting tempTodos equal to todos. This isn't
making a copy of the original array but rather a reference. In order to create
a copy I am adding the .slice() at the end. This will create a copy.
This one used to get me all of the time.
*/
let tempTodos = todos.slice();
tempTodos[index].done = true;
setTodos(tempTodos);
}
console.log(todos)
return (
<div>
<h1>Hello, world!</h1>
<div>
{todos.map((todo,index) => {
return todo.done ? (<div key={index}>{todo.name} : done</div>) : (<div onClick={() => handleClick(todo.name)} key={index}>{todo.name} : not done</div>)
})}
</div>
</div>
)
}


ReactDOM.render(
<App />,
document.getElementById('root')
);

我做的另一件事是简化由 map 创建的 div 的键。我只是将索引添加到 map 并将其用作键,这样就干净多了。

希望这对您有所帮助!

关于reactjs - 映射对象数组状态时如何重新渲染 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58151577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com