简体   繁体   English

组件 state 从 function 切换到渲染组件

[英]Component state switching from function to render component

I am currently trying to use some data that I receive from an api in my render method.我目前正在尝试在我的渲染方法中使用从 api 收到的一些数据。 I am calling the function in my componentDidMount.我在 componentDidMount 中调用 function。 Here is the function:这是 function:

 getDataFromDb = () => {
        axios.get(this.props.urlFromParent + "GetCurrentPods/Device1")
            .then( (res) => {
                this.setState({
                    Pods : res.data
                })
                console.log(this.state.Pods)
            })
 };

and I am calling it in my render method like this我在我的渲染方法中这样调用它

{console.log('hello'+ this.state.Pods)}

here is the console.log outputs:这是 console.log 输出:

hello[object Object]
Array [
Object {
    "ParentDeviceID": "Device1",
    "ParentDeviceIsActive": true,
    "PodIsActive": true,
    "PodLocation": 5,
    "PodType": 2,
    "__v": 0,
    "_id": "5d6bfe9c50a6c33006cbd6ac",
},
]

I cant figure out why the state is returning object Object in the render method.我无法弄清楚为什么 state 在渲染方法中返回 object Object。 Also i am receiving the error: Warning: Cannot update during an existing state transition (such as within render ).我也收到错误:警告:在现有的 state 过渡期间无法更新(例如在render中)。 Render methods should be a pure function of props and state I'm not sure if this has anything to do with my problem.渲染方法应该是纯 function 的道具和 state我不确定这是否与我的问题有关。 Thanks for any help.谢谢你的帮助。

console.log('hello'+ this.state.Pods)

The above line will convert the object to a string as you are concatenating the string "hello" with an object "this.state.Pods".当您将字符串“hello”与 object “this.state.Pods”连接时,上述行会将 object 转换为字符串。 You should use, or two console statements to logging hello and this.state.Pods differently.您应该使用,或两个控制台语句以不同方式记录 hello 和 this.state.Pods。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM