簡體   English   中英

如何在獲取請求和 state 更改后重新渲染組件?

[英]How to re-render component after fetch request and state change?

我是新來的反應和后端綁定,但在我提出獲取請求后,我必須重新加載頁面以查看任何更改。 一旦調用函數,數據庫就會更新,但組件不會重新呈現。 我知道 setState 是異步工作的,所以我嘗試在 setState 的回調中調用我的函數,但這不起作用。

這發生在我的handleSubmithandleDelete函數上。 我的初始獲取請求在我的 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>

我正在尋找的結果是一旦我添加了一個待辦事項,它就會立即呈現在我的列表中,而不僅僅是在頁面重新加載時。

在請求中從后端返回詳細信息,使用該值更新 state,

目前您只是在后端執行操作,前端不知道它發生在后端。 最好的方法是在對數據庫執行操作后將完整數據(列表或對象)傳回前端,並將值鏈接到 state,如果數據是大容量的,則發送成功消息(200 就足夠了)返回從后端到前端,如果成功更改前端的值(列表),則將值(列表)鏈接到前端的 state 以重新渲染組件。

你必須更新你的 state,一旦你更新 state,你的組件將重新渲染,它會顯示最新的更改。 在這里,我假設您在 state 中設置的“待辦事項”是一個數組,然后在刪除和添加時對其進行更新。 IE:

  // 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})
      })
     };

您可能沒有更改您的 state “todos”,這就是它不渲染的原因。 您可以在每次更改后獲取待辦事項(在刪除、更新、添加......之后)或自己更改 state。

方法一:

componentDidMount() {
    this.getTodos();
}

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

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

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

方法二:

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});
}

暫無
暫無

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

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