从显示错误的状态反应创建 JSX

React creating JSX from state showing error

在我的 React 应用程序中,在页面加载时,我调用 API 并将该值存储在状态中。当我尝试从状态创建 JSX 元素时出现错误 Cannot read properties of undefined (reading 'expire').

const [domains, setDomains] = useState([]);
const [records, setRecords] = useState({});

useEffect(() => {
        axios.get('zones/domains').then((res) => {
            setDomains(res.data)
            axios.get('zones/records', {
                params: {
                    l_id: res.data[0].l_id
                }
            }).then((res) => {
                setRecords(res.data)
            });
        });
        
    }, [])


let table_str = <tr>
    <td>SOA</td>
    <td>{records.added.expire}</td>
    <td>{records.added.value1} {records.added.value2}</td>
</tr>

在 axios 调用之前你的状态是空的。确保通过可选更改进行如下更新。

let table_str = <tr>
    <td>SOA</td>
    <td>{records?.added?.expire}</td>
    <td>{records?.added?.value1} {records?.added?.value2}</td>
</tr>