【问题标题】:Hook is not called more than 1 timeHook 被调用不超过 1 次
【发布时间】:2020-03-10 19:11:02
【问题描述】:

我正在构建一个简单的 ToDoList 应用程序。 我使用 React Hook 获取列表。 当我添加新的 Todo 或删除现有的 Todo 时,请求会发送并正常工作,但组件不会重新呈现。 我尝试了 2 种方法来解决创建问题 1.异步函数(删除和添加)。将 getToDoList 置于钩子之外并在请求后调用它(发布/删除)

 useEffect(() => {
    getToDoList();
}, []);


const getToDoList = async () => {
    const result = await axios.get('http://localhost:1200/');
    setToDoList(result.data);
};

const addNewTodo = async () => {
    await axios.post('http://localhost:1200/create', {
        item: newToDo.current.value
    });
    getToDoList();
};

const deleteToDo = async (id) => {
    await axios.delete(`http://localhost:1200/delete?id=${id}`);
    getToDoList();
};

2.在钩子中获取getToDoList并给它2个依赖项,这些依赖项在deleteToDo/addNewToDo中发生了变化

const [add, setAdd] = useState(false);
const [remove, setRemove] = useState(false);

useEffect(() => {
    const getToDoList = async () => {
        const result = await axios.get('http://localhost:1200/');
        setToDoList(result.data);
    };
    getToDoList();
}, [add, remove]);

const addNewTodo = async () => {
    await axios.post('http://localhost:1200/create', {
        item: newToDo.current.value
    });
    setAdd(!add);
};

const deleteToDo = async (id) => {
    await axios.delete(`http://localhost:1200/delete?id=${id}`);
    setRemove(!remove);
};

两者都不起作用。请告诉我我哪里错了

JSX

 return (
    <div>
        <Jumbotron>
            <Container>
                <h1>Hello!</h1>
                <p>This is a simple ToDoList created by Vadik</p>
            </Container>
        </Jumbotron>
        <Container>
            <Container>
                <InputGroup>
                    <FormControl placeholder="What needs to be done" ref={newToDo}/>
                </InputGroup>
                <Button onClick={addNewTodo} variant="primary" size="sm">
                    Add new Todo
                </Button>
            </Container>
            <Container className="cards">
                <Card>
                    <ListGroup>
                        {toDoList.todos.map((elem) => <ListGroup.Item
                            key={elem._id}>{elem.item}<CloseButton onClick={() => deleteToDo(elem._id)}/>  </ListGroup.Item>)}
                    </ListGroup>
                </Card>
            </Container>
        </Container>
    </div>
);

【问题讨论】:

  • 请分享绑定到你所在州的jsx
  • @Chev Shared,看
  • 您是否尝试将setToDoList(result.data);getToDoList() 放入then-block 中?
  • setToDoList函数的定义是什么?
  • @NikaTsogiaidze const [toDoList, setToDoList] = useState({todos: []}); const newToDo = useRef("");

标签: reactjs async-await axios react-hooks use-effect


【解决方案1】:

试试下面的代码。这应该可以工作。在 addTodo 中,有两种方法可以在 post 成功后更新 resultList 或使用 getList 获取最新数据并更新 resultList。两者都显示了。

    function Example() {

      const [resultList, setResult] = useState({todos: []});

      useEffect(() => {
        const todoList = getToDoList();
        setResult(prev => todoList);
      }, []);

      const addTodo = async () => {
        await axios.post('http://localhost:1200/create', {
          item: newToDo.current.value
        });

        //Addition successful, hence update our resultList.
        return setResult(prev => {
          return {todos: [...prev.todos, {item: newToDo.current.value, id: prev.todos.length+1}]}
        });


        //Now since add api doesn't return a 
        //value call Get api again and update the todoList to render
        //const todoList = getToDoList();
        //setResult(prev => todoList);
      };

      const getToDoList = async () => {
        const result = await axios.get('http://localhost:1200/');
        return result.data;
      };          

      return (
        <div id='container'>
          {resultList.todos.map(todo => <div>{todo.item}</div>
          )}
          <button onClick={addTodo}>Add</button>
        </div>
      )


    }

【讨论】:

    【解决方案2】:

    问题是我没有对这些请求发送任何响应。enter image description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2016-01-09
      • 2017-01-03
      • 1970-01-01
      相关资源
      最近更新 更多