简体   繁体   English

从 axios 获取数据时,react hook 的 useState() 方法的奇怪行为

[英]Strange behavior of useState() method of react hook while fetching data from axios

I am using axios library to fetch data from a json file through json-server.我正在使用 axios 库通过 json-server 从 json 文件中获取数据。 When I am loading and using the response object in a single component it is working perfectly.当我在单个组件中加载和使用响应 object 时,它运行良好。 But when I am passing this response object to child component from parent component it is not loading the data.但是,当我将此响应 object 从父组件传递给子组件时,它不会加载数据。 Also not receiving any errors, can someone please help me to understand the difference and what is wrong with my approach?也没有收到任何错误,有人可以帮我理解差异以及我的方法有什么问题吗?

//Scenario-1 : working perfectly fine:

import React, { useState, useEffect } from 'react';
import Display from './Display';
import Note from './note'
import axios from 'axios';

const App = () => { 
  const [notes, setNotes] = useState([])

  const hook = () => {
      axios.get('http://localhost:3001/notes')
        .then(response => {
        setNotes(response.data)
      })
  }

  useEffect(hook, [])

  return (
    <div>     
        {notes.map(n => <Note key={n.id} note={n} />)}
    </div>
  )
}

export default App;


//Scenario-2 : Not working as expected, also no errors.
const Display = (props) => {    

    //Receiving data here, can see the values in console.
    console.log('inside display, props.notex: ', props.notex); 

    const [notes, setNotes] = useState(props.notex);

    //Blank object, why useState() method is not setting the value of "notes" from "props.notex".
    console.log('inside display, notes: ', notes); 

    const generateRows = () => {
        console.log('generateRows: ', notes)
        return (
            notes.map(n => <Note key={n.id} note={n} />)
        )
    }

    return (
        <div>            
            <ul>
                {generateRows()}
            </ul>           
        </div>
    )
}

const App = () => { 
  const [notes, setNotes] = useState([])

  const hook = () => {
      axios.get('http://localhost:3001/notes')
        .then(response => {
        setNotes(response.data)
      })
  }

  useEffect(hook, [])

   return (
    <div>                            
        <Display notex={notes} />        
    </div>
  )
}

export default App;

My guess is that useState is asynchronous, same as setState in Class components.我的猜测是useState是异步的,与 Class 组件中的setState相同。 Due to its async nature, you are not able to log anything - the log gets executed before the useState actually does anything.由于其异步性质,您无法记录任何内容 - 在 useState 实际执行任何操作之前执行日志。

If you really want to do it this way, you could initialize the value of the useState as an empty array and set up a useEffect hook, with the props.notex in your dependency array, something like this:如果你真的想这样做,你可以将 useState 的值初始化为一个空数组并设置一个 useEffect 钩子,在你的依赖数组中使用props.notex ,如下所示:

useEffect(() => {
  if (props.notex) setNotes(props.notex)
}, [props.notex])

And then in the return然后在返回

return (
        <div>            
            <ul>
                {notes.length && generateRows()}
            </ul>           
        </div>
    )

But you could just pass the props down from the parent to child without setting the state in the child component.但是您可以将道具从父级传递给子级,而无需在子组件中设置 state。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 usestate 钩子在反应中不起作用 - the usestate hook is not working in react 使用 React 上的自定义钩子获取数据 - Fetching Data using custom hook on React 从 api(php) 获取数据时在 http 方法中键入错误 - Type error in http method while fetching data from api(php) 为什么我需要使用 && 操作数来检查来自 useState 钩子的数据? - Why I need to use && operand to check data from useState hook? 使用反应钩子获取数据在嵌套的 obj 属性上返回 undefined - fetching data with react hook returns undefined on nested obj properties 使用 axios 从本地 JSON 文件中获取数据并显示数据 - Fetching data from local JSON file using axios and displaying data 当我从react中的表单更新状态时,子组件中的数据会出现奇怪的行为 - When I update my state from form in react, my data in child components, gets strange behavior 反应:在 map 中获取并修改 useState 数组 - React: Fetching inside a map and modifying a useState array 如何从 json 中分离键和值,并在反应中使用 useState 挂钩将其存储在数组中 - How to seperate keys and values from a json and store it in a array using useState hook in react 在反应“Uncaught TypeError: Cannot read properties of undefined”中从 api 获取数据时出错 - Error while fetching data from api in react "Uncaught TypeError: Cannot read properties of undefined"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM