我试图映射处于状态的对象数组,有条件地从该状态返回两个反应组件之一。然后,我会在某个时候更改该状态,并希望该组件在对象状态更改后重新呈现。我知道我的问题与React无法识别差异的变化有关,但是我不确定为什么以及为实现此功能需要更改的模式。
这是一个codepen: 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>
)
}
答案 0 :(得分:3)
在这里,这现在应该为您工作。我在那里添加了一些笔记。
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')
);
我要做的另一件事是简化由地图创建的div的键。我只是将索引添加到地图上,并将其用作键,这样更清洁了。
希望这会有所帮助!
答案 1 :(得分:0)
React不会将状态更改为 。
const handleClick = n => setTodos(todos.map(t => t.name === n ? {...t, done: true} : t));