如何通过挂钩更新对象状态

时间:2020-02-19 17:09:48

标签: javascript reactjs react-hooks

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

我刚刚开始使用钩子,我喜欢它如何允许使用简单的纯JavaScript函数和useState()函数来创建和管理状态,以及使用{{1 }}函数,但是我似乎无法使状态更新正常!

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

enter image description here

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

App

3 个答案:

答案 0 :(得分:2)

您的代码中有3个错误

import json
my_dict = json.loads('{"user_id": "Mane", "name": "Joe"}')
my_dict['user_id']

答案 1 :(得分:2)

您可以改善以下几点:

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

没有状态对象

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

答案 2 :(得分:0)

使用钩子更新对象以将函数语法用于setState回调的正确方法:

setData(prevState => {...prevState, placeholder: 'Something went wrong'})

以下方法将覆盖您先前的对象状态:

setData({placeholder: 'Something went wrong'}); // <== incorrect

您的最终代码应如下所示:

.then(response => {
    if (response.status !== 200) {
        setData(prevObj => {...prevObj, placeholder: 'Something went wrong'});
    }
    return response.json()
 })
.then(result => {
    setData(prevObj => {...prevObj, data: result});
 });