映射对象数组的状态时如何重新渲染反应组件

Ste*_*low 2 reactjs react-hooks

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

这是一个代码笔: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>
  )
}
Run Code Online (Sandbox Code Playgroud)

小智 6

给你,这里现在应该对你有用。我在里面加了一些注释。

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')
);
Run Code Online (Sandbox Code Playgroud)

我做的另一件事是简化地图创建的 div 的键。我只是将索引添加到地图中并将其用作键,这样更清晰。

希望这可以帮助!