通过辅助函数进行渲染时,我得到:“对象作为React子对象无效”错误

时间:2018-09-02 09:48:12

标签: javascript reactjs react-native

我正在用React Native开发一个小项目。我注意到一种奇怪的情况,当我通过助手功能呈现列表时,出现同义错误:

  

对象无效,不能作为React子对象

现在,此错误通常意味着我正在尝试渲染对象,事实并非如此。我将粘贴两个代码段。第一个是我如何通过帮助程序功能(由于错误而导致)呈现数据。第二个片段是如何直接在render()方法中呈现数据并成功工作。

代码段1::无法通过辅助功能renderUsers()->渲染

  renderUsers = async () => {
    return this.props.userList.map(
      ({ instructions, address, createdDate, _id }) => (
        <Card
          title={`${moment(createdDate).format("YYYY-MM-DD HH:mm")}`}
          key={_id}
        >
          <Text style={{ marginBottom: 10 }}>{instructions}.</Text>
          <Button backgroundColor="#03A9F4" title="Ready to Help!" />
        </Card>
      )
    );
  };
  ...
  render() {
    return this.props.isFetchingUsers ? null : (
      <View style={{ flex: 1 }}>
        <ScrollView>
          {this.renderUsers()}
        </ScrollView>
      </View>
    );
  }

代码段2:直接在render()函数内部进行渲染->正常运行

  render() {
    return this.props.isFetchingUsers ? null : (
      <View style={{ flex: 1 }}>
        <ScrollView>
          {this.props.userList.map(
            ({ instructions, address, createdDate, _id }) => (
              <Card
                title={`${moment(createdDate).format("YYYY-MM-DD HH:mm")}`}
                key={_id}
              >
                <Text style={{ marginBottom: 10 }}>{instructions}.</Text>
                <Button backgroundColor="#03A9F4" title="Ready to Help!" />
              </Card>
            )
          )}
        </ScrollView>
      </View>
    );
  }

可能是什么原因?

3 个答案:

答案 0 :(得分:2)

您的代码段1应该是这样的。

with open(self.usersfile, 'rt') as f:

您需要删除关键字renderUsers = () => { return this.props.userList.map( ({ instructions, address, createdDate, _id }) => ( <Card title={`${moment(createdDate).format("YYYY-MM-DD HH:mm")}`} key={_id} > <Text style={{ marginBottom: 10 }}>{instructions}.</Text> <Button backgroundColor="#03A9F4" title="Ready to Help!" /> </Card> ) ); }; ... render() { return this.props.isFetchingUsers ? null : ( <View style={{ flex: 1 }}> <ScrollView> {this.renderUsers()} </ScrollView> </View> ); }

答案 1 :(得分:2)

异步函数将返回Promise对象,该对象不应该是React子代。

但是您不需要async函数用于数组映射。

如果要渲染asynchronously,请尝试用this.setState更新状态并相应地渲染。

答案 2 :(得分:0)

您不应在渲染方法中返回null!

您应该渲染这样的元素:

  render() {
    <View style={{ flex: 1 }}>
      <ScrollView>
        { 
          (!this.props.isFetchingUsers && this.props.userList) &&
          this.renderUsers()
        }
      </ScrollView>
    </View>
  }

然后从async方法中删除关键字renderUsers