如何通过钩子更新反应中的对象状态

Rom*_*meo 3 javascript reactjs react-hooks

这是一个简单的问题。如何通过反应钩子成功更新状态对象?

我刚刚开始使用钩子,我喜欢它如何允许使用简单而纯的 JavaScript 函数来创建和管理该useState()函数的状态,并且还可以使用useEffect()函数进行影响组件的更改,但我似乎无法进行更新为国家工作!

向 API 发出请求后,它会返回所需的数据,但是当我尝试更新请求中的错误和成功请求的状态时,它不会更新状态。我将其记录到浏览器控制台,但状态没有发生任何更改,它返回未定义。

在此输入图像描述

我知道我在代码中没有做正确的事情。这是我的App组件,它是用于获取和更新的单个组件:

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';


export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading' 
    });

    // Fetch and update date
    useEffect(() => {

        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                SetData({placeholder: 'Something went wrong'});
            }
            response.json()
        })
        .then(result => {
           console.log(data);
           setData({data: result});
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}

ReactDOM.render(<App />, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)

Lin*_*ger 5

您可以改进以下几点:

  • React-hook useState 的行为与对应的类不同。它不会自动将提供的对象与状态合并,您必须自己执行此操作。
  • 我建议您是否可以在没有对象作为状态的情况下进行工作,因为这可以大量减少重新渲染的数量,并且可以更轻松地更改状态的形状,因为您只需添加或删除变量即可并立即查看所有用法。

带有状态对象

export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading' 
    });

    // Fetch and update date
    useEffect(() => {
        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                throw new Error(response.statusText); // Goto catch block
            }
            return response.json(); // <<- Return the JSON Object
        })
        .then(result => {
           console.log(data);
           setData(oldState => ({ ...oldState, data: result})); // <<- Merge previous state with new data
        })
        .catch(error => { // Use .catch() to catch exceptions. Either in the request or any of your .then() blocks
            console.error(error); // Log the error object in the console.
            const errorMessage = 'Something went wrong';
            setData(oldState=> ({ ...oldState, placeholder: errorMessage }));
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}
Run Code Online (Sandbox Code Playgroud)

没有状态对象

export default function App() {
    const [data, setData] = useState([]);
    const [loaded, setLoaded] = useState(false);
    const [placeholder, setPlaceholder] = useState('Loading');

    // Fetch and update date
    useEffect(() => {
        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                throw new Error(response.statusText); // Goto catch block
            }
            return response.json(); // <<- Return the JSON Object
        })
        .then(result => {
           console.log(data);
           setData(data);
        })
        .catch(error => { // Use .catch() to catch exceptions. Either in the request or any of your .then() blocks
            console.error(error); // Log the error object in the console.
            const errorMessage = 'Something went wrong';
            setPlaceholder(errorMessage);
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}
Run Code Online (Sandbox Code Playgroud)