获取请求和状态更改后如何重新渲染组件?

问题描述 投票:0回答:3

我是后端反应和绑定的新手,但在发出获取请求后,我必须重新加载页面才能看到任何更改。一旦调用函数,数据库就会更新,但组件不会重新渲染。我知道 setState 是异步工作的,所以我尝试在 setState 的回调中调用我的函数,但这不起作用。

这发生在我的

handleSubmit
handleDelete
函数上。我的初始获取请求位于我的 componentDidMount 中,因此我将其包含在内,以防它有帮助。

我在网站上找不到我需要的答案,也许推荐已经消失了,但我在这里,哈哈。预先感谢。

     componentDidMount() {
          // todos is the data we get back
          // setting the state to newly aquired data
          fetch("/api/todos")`enter code here`
               .then(res => res.json())
               .then(todos => this.setState({ todos }, () => 
               console.log("Todos fetched...", todos)))
               .catch(err => console.log(err))
    
      }
    
    
    // onClick for submit button
        handleSubmit = (e) => {
            e.preventDefault();
            const data = this.state;
            fetch("/api/todos", {
                method: "post",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
        };
    
    
    // onClick for delete button
         handleDelete = (e) => {
            e.preventDefault();
            let uniqueId = e.target.getAttribute("id")
            fetch(`/api/todos/${uniqueId}`, {
                method: "delete",
                headers: { 'Content-Type': 'application/json' }
            })
         };
    
    // Some of the JSX if needed
         <DeleteBtn
             id={todo._id}
             onClick={this.handleDelete}
         >X</DeleteBtn>
    
    <Form onSubmit={this.handleSubmit} id="myForm"></Form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我正在寻找的结果是一旦我添加了一个待办事项,它就会立即呈现在我的列表上,而不是仅在页面重新加载时呈现。

javascript node.js reactjs mongodb fetch
3个回答
0
投票

从请求中的后端返回详细信息,使用该值来更新状态,

目前你只是在后端进行操作,前端并不知道发生在后端。 最好的方法是在数据库上执行操作后将完整数据(列表或对象)传递回前端并将值链接到状态, 如果数据量很大,则从后端向前端发送一条成功消息(200 就足够了),如果成功则更改前端的值(列表), 将值(列表)链接到前端的状态以重新渲染组件。


0
投票

您必须更新您的状态,一旦您更新状态,您的组件将重新渲染并显示最新的更改。 在这里,我假设您在状态中设置的“todos”是一个数组,然后只需在删除和添加时更新它。 即:

  // onClick for submit button
    handleSubmit = (e) => {
        e.preventDefault();
        const data = this.state;
        const currentTodos = [...this.state.todos]
        fetch("/api/todos", {
            method: "post",
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        }).then(()=>{
           currentTodos.push(data);
           this.setState({todos:currentTodos})
        })
    };
 // similarly for delete you can do

 // onClick for delete button
     handleDelete = (e) => {
        e.preventDefault();
        let uniqueId = e.target.getAttribute("id")
        let currentTodos = [...this.state.todos];
        fetch(`/api/todos/${uniqueId}`, {
            method: "delete",
            headers: { 'Content-Type': 'application/json' }
        }).then(()=>{
         let updatedTodos = currentTodos.filter(todo=>todo._id !==uniqueId);
         this.setState({todos:updatedTodos})
      })
     };

0
投票

您可能没有更改您的状态“todos”,这就是它不渲染的原因。您可以在每次更改后(删除、更新、添加...之后)获取待办事项或自行更改状态。

方法一:

componentDidMount() {
    this.getTodos();
}

getTodos = () => {
    //fetch todos, setState
}

handleSubmit = () => {
    fetch(...).then(this.getTodos);
}

handleDelete = () => {
    fetch(...).then(this.getTodos);
}

方法2:

componentDidMount() {
    this.getTodos();
}

getTodos = () => {
    //fetch todos, setState
}

handleSubmit = () => {
    fetch(...);
    let todos = this.state.todos;
    todos.push(newTodo);
    this.setState({todos});
}

handleDelete = () => {
    fetch(...);
    let todos = this.state.todos;
    //remove todo from todos
    this.setState({todos});
}
© www.soinside.com 2019 - 2024. All rights reserved.