React(Native):传递具有从异步函数获得的值的prop

时间:2019-02-01 19:37:31

标签: javascript reactjs react-native

我正在使用React Native。

我想将道具从组件(在此示例中为Father)传递到其子代。这样的prop的值应该是一个字符串,并且我想将计算该字符串的值的逻辑封装在一个函数中(在此示例中为favoriteIconHandler)。

但我不能设法通过由该函数返回字符串favoriteIconHandler。我似乎永诺通过其中一个功能或一个对象,从而产生这样的信息:

Warning: Failed prop type: Invalid prop `name` of value `function proxiedMethod() {
    [native code]
}` supplied to `Icon`, expected one of ["3d-rotation","ac-unit",

这是我正在使用的代码:

export default class Father extends React.Component {

    constructor(props) {
        super(props);
        this.favoriteIconHandler = this.favoriteIconHandler.bind(this);
    }

    async favoriteIconHandler (name) {
        let isFavorite = false;
        try {
            const favorites = await AsyncStorage.getItem('favorites') || 'none';
            isFavorite = favorites.includes(name);
        } catch (error) {
          console.log(error.message);
        }

        let icon = 'star-border';
        if (isFavorite) icon = 'star';
        return icon
    };

    render() {
        // ...
        return (
            <ScrollView>
                <View>
                    <DetailListItem
                        icon={this.favoriteIconHandler(name)} // this function call is not working as expected
                    />
                </View>
            </ScrollView>
        );
    }
}

所以我的问题是,我应该如何调用favoriteIconHandler函数以获取返回的字符串并将其作为道具传递?

2 个答案:

答案 0 :(得分:2)

由于您的favoriteIconHandler()方法是一个async函数,因此它将返回一个Promise,因此您的<DetailListItem>基本上是这样的:

<DetailListItem icon={Promise.resolve()} />

您可以做的是使用组件状态来传递默认值,当承诺解决时,您可以对其进行更新:

export default class Father extends React.Component {
  state = { icon: 'star-border' }

  componentDidMount() {
    await favoriteIconHandler(); // pass a name here?
  }

  async favoriteIconHandler (name) {
    try {
      const favorites = await AsyncStorage.getItem('favorites') || 'none';

      favorites.includes(name) && this.setState(() => ({
        icon: 'star',
      });
    } catch (error) {
      console.log(error.message);
    }
  };

  render() {
    const { icon } = this.state;

    return (
      <ScrollView>
        <View>
          <DetailListItem icon={icon} />
        </View>
      </ScrollView>
    );
  }
}

答案 1 :(得分:1)

我看到这是如何设置的两个问题。

根据javascript documentation,必须在其前面的await处调用异步函数。现在如何使用它,您要使用异步功能,但是您不必等待它完成。 但是,我什至不确定更改是否有效。

更好的解决方案是将函数本身作为道具传递。 IE在detailListItem上添加了一个道具,称为iconGetterFunction={this.favoriteIconHandler}。然后在detailListItem组件的componentDidMount中或您可以调用的内容

let result = await props.iconGetterFunction()

在这一点上,使用结果,你会。