首页 > 解决方案 > 无法从后端使用 React.js 设置数据

问题描述

这是来自后端数据格式: 在此处输入图像描述


{数据:数组(15)}

 data[0]:

        option: Array(1)

                           0: "String"

        _id: "String"

        col1: "String"

        col2: "String"

        col3: "String"

....数据[14]


这是前端代码:

 const Component1 = () => {
    const [dbvalue, setDbvalue] = useState(null)

    //option, _id, col1, col2, col3
    const getAlldbValue = async () => {
        try {
            const resp = await services.getAlldbValue();
            console.log(resp) //enter F12 can get total data from back end. 
            setDbvalue(resp.data.data) 
            console.log(dbvalue) //setDbvalue() not work , this print null 
        } catch (error) {
            console.log(error)
            alert('Failed!')
        }
    }

    useEffect(() => {
        getAlldbValue()
      }, [])

      if(!dbvalue) {
        return (
              <p>Loading Component...</p> //not appear
        )
      }
    return (
        <p>{dbvalue}</p> //not appear
    );
};

export default Component1;

如何将此嵌套对象 json 设置到此 dbvalue 中?我想使用 dbvalue.keyname 来显示。谢谢你的帮助

标签: reactjsaxiosreact-hooks

解决方案


首先,您的 console.log 打印 null 因为当您使用 setState 时,您刚刚设置的变量只会在下一次渲染中设置。尝试打印resp.data.data而不是放在函数console.log(dbvalue)之外getAlldbValue,这样您可以更好地理解。

还,

`return (
    <p>{dbvalue}</p> //not appear
);` 

您尝试将对象放入 HTML 元素中,尝试dbvalue[0].col1或您想要显示的任何内容。

希望它可以帮助你。


推荐阅读