【问题标题】:Why does the string come as an object React Native?为什么字符串作为 React Native 对象出现?
【发布时间】:2020-10-14 11:24:12
【问题描述】:

我通过 api 绘制一个字符串值,我想在 View 中打印它。但是传入的字符串值以 Promise 的形式出现。我怎样才能防止这种情况发生?

“不变违规:对象作为 React 子对象无效(发现:对象具有键 {_40, _65,_55, _72}=。如果您要渲染子对象集合,请改用数组。”

async getTitle(id) {        
    try {
        const username = await AsyncStorage.getItem('username');
        const token = await AsyncStorage.getItem('token');            

        if(token) {
            var credentials = Base64.btoa(username + ':' + token);
            var URL         = `https://portal.xxxxx.com/api/v1/User/${id}`;
                
            var title = await axios.get(URL, {headers : { 'Espo-Authorization' : credentials }})
            .then((res) => {
                return <Text>{res.data.title}</Text>
            })
            .catch((err) => {
                console.log(err);
            });

            return title;
        }
    }catch (err) {
        console.log(err);
    }
}

<List
    contentContainerStyle={styles.listContentContainer}
    data={stream}
    ItemSeparatorComponent={Divider}
    renderItem={({ item, index }) => (
        item.type === "Post" ?
        <ListItem
            key={index}
            title={<Text><Text style={{ fontSize: 12 }}>{item.createdByName}</Text> {this.getTitle(item.createdById)} {'\n'} <Text style={{ fontSize: 12 }}>{Moment(item.createdAt).add(3, 'hours').format('lll')}</Text>{'\n'}<Text style={{ fontSize: 12 }} status="warning">{this.statusLanguage(status)}</Text></Text>}
            description={<Text style={{ fontSize: 15 }}>{item.post}</Text>}
            accessoryLeft={renderCommentIcon}
        /> : null
    )}
/>

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    由于您正在进行异步调用,因此结果是 Promise。您可以使用 useState 定义一个值:

    [title, setTitle] = useState('');

    你可以在你的 Promise 解决后使用setTitle。通过这样做,您的组件将被重新渲染,并且生成的标题值可以显示在视图中。

    【讨论】:

    • 我已经知道了。但不止一件我的物品要来了。状态只能保存 1 个值。
    • 然后使用 titles 代替 title,这是一个保存所有值的数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    相关资源
    最近更新 更多