gpt4 book ai didi

javascript - react ( native ): Pass a prop with the value obtained from an async function

转载 作者:行者123 更新时间:2023-11-28 17:10:50 24 4
gpt4 key购买 nike

我正在使用 React Native。

我想将一个 prop 从组件(本例中为 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 函数才能获取它返回的字符串并将其作为 Prop 传递?

最佳答案

自从您的 favoriteIconHandler()方法是async函数,它返回 Promise ,所以你的<DetailListItem>基本上看起来像这样:

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

您可以做的是使用组件状态传递默认值,当 Promise 解析时,您可以更新它:

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>
);
}
}

关于javascript - react ( native ): Pass a prop with the value obtained from an async function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54486138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com