【问题标题】:Component state switching from function to render component组件状态从函数切换到渲染组件
【发布时间】:2019-09-18 20:13:47
【问题描述】:

我目前正在尝试在我的渲染方法中使用从 api 接收到的一些数据。我在我的 componentDidMount 中调用该函数。这是函数:

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

我在我的渲染方法中这样调用它

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

这是 console.log 输出:

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

我无法弄清楚为什么状态在渲染方法中返回对象 Object。 我也收到错误: 警告:在现有状态转换期间无法更新(例如在render 内)。渲染方法应该是 props 和 state 的纯函数 我不确定这是否与我的问题有关。感谢您的帮助。

【问题讨论】:

  • 请发布您的渲染方法
  • render() { return ( {console.log('hello'+ this.state.Pods)} ); }
  • 我故意将所有内容都标记出来,因为我假设它会是别的东西。
  • {console.log('hello'+ this.state.Pods)} 会将 Pods 值转换为字符串。当一个对象转换为字符串时,它看起来像[object Object]

标签: reactjs react-native


【解决方案1】:
console.log('hello'+ this.state.Pods)

当您将字符串“hello”与对象“this.state.Pods”连接时,上述行会将对象转换为字符串。您应该使用 , 或两个控制台语句以不同的方式记录 hello 和 this.state.Pods。

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2018-03-24
    • 2019-11-09
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多