【问题标题】:Handling PHP response with Axios/React Native使用 Axios/React Native 处理 PHP 响应
【发布时间】:2022-01-10 07:35:52
【问题描述】:

我是 React Native 初学者,请原谅基本问题。我在使用 axios get 处理从 PHP 返回的 json 时遇到问题。

我的 php 返回(已尝试使用和不使用 headers 部分,也尝试使用/不使用 json_encode):

<?php

 $json ="[{
        id: 1,
        title: 'List Item One',
        description: 'test1'
    },
    {
        id: 2,
        title: 'List Item Two',
        description: 'test2'
    }]";


header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);

下面是我的 react native 函数(我要开始工作的部分已被注释掉)


    const [messages, setMessages] = useState([]);

    useEffect(() => {
        loadMessages();
    }, []);

    const loadMessages = async () => {

        let res = await axios.get('https://example.com/test_messages.php');
        //setMessages(res.data);
        console.log(res.data);
    }

    return (
        <Screen style={styles.screen}>

        <FlatList 
        
        data={messages}
        keyExtractor={message => message.id.toString()}
        renderItem={({item}) => (

console.log 似乎工作并返回:

[{
        id: 1,
        title: 'List Item One',
        description: 'test1'
    },
    {
        id: 2,
        title: 'List Item Two',
        description: 'test2'
    }]

但是当我尝试改用注释部分时,我得到了这个错误:

“未定义不是对象('评估 message.id.toString')”

似乎只是在格式化输出,因为 console.log 看起来不错。此外,当我将数组硬编码为变量并在 useState 函数中使用它时,它也可以正常工作。

【问题讨论】:

    标签: php react-native axios


    【解决方案1】:

    这个json的格式可能不正确,你可以在https://jsonlint.com/查看。正确的格式应该像下面JSON.stringify的输出

    【讨论】:

    • 我试过没有json_encode,然后又试了一次,没用。也试过同时删除 json_encode 和 headers,没用。
    • 删除json_encode后出现什么错误?
    • 和以前一样
    • 我也试过 JSON.stringify 但会再试一次
    • 解决了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多