簡體   English   中英

反應useState鈎子不更新狀態

[英]React useState hook isn't updating the state

我遇到了useState問題。 下面是在codesandbox中運行的代碼

https://codesandbox.io/s/kmznl0345r

這是代碼本身;

import React, { Fragment, useState } from "react";
import ReactDOM from "react-dom";

type FormElem = React.FormEvent<HTMLFormElement>;

interface ITodo {
  text: string;
  complete: boolean;
}

export default function App(): JSX.Element {
  const [value, setValue] = useState<string>("");
  const [todos, setTodos] = useState<ITodo[]>([]);

  const handleSubmit = (e: FormElem): void => {
    e.preventDefault();
    addTodo(value);
    setValue("");
  };

  const addTodo = (text: string): void => {
    const newTodos: ITodo[] = [...todos, { text, complete: false }];
    setTodos(newTodos);
  };

  const completeTodo = (index: number): void => {
    const newTodos: ITodo[] = todos;
    newTodos[index].complete = !newTodos[index].complete;
    setTodos(newTodos);
  };

  return (
    <Fragment>
      <h1>Todo List</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={value}
          onChange={e => setValue(e.target.value)}
          required
        />
        <button type="submit">Add Todo</button>
      </form>
      <section>
        {todos.map((todo: ITodo, index: number) => (
          <Fragment key={index}>
            <div>{todo.text}</div>
            <button type="button" onClick={() => completeTodo(index)}>
              {" "}
              {todo.complete ? "Incomplete" : "Complete"}{" "}
            </button>
          </Fragment>
        ))}
      </section>
    </Fragment>
  );
}

const root = document.getElementById("root");

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

單擊完成按鈕時,它僅運行一次completeTodo函數,即使setTodos函數已運行並且待辦事項已更新,它也不會再次運行。

這曾經在react 16.7.0-alpha-2起作用,但現在在16.8.1版本中似乎沒有更新。

讓我知道您有任何建議,這里再次是在codeandbox中運行的代碼;

https://codesandbox.io/s/kmznl0345r

您當前正在您的completeTodo函數中todo對象。 如果改為使用todos所有元素創建一個新數組,並在切換complete位置創建一個新對象,則它將按預期工作。

const completeTodo = (index: number): void => {
  const newTodos: ITodo[] = [...todos];
  newTodos[index] = {
    ...newTodos[index],
    complete: !newTodos[index].complete
  };
  setTodos(newTodos);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM