React 从显示错误的状态创建 JSX

use*_*835 2 javascript reactjs react-state

在我的 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>
Run Code Online (Sandbox Code Playgroud)

Obs*_*lab 5

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

let table_str = <tr>
    <td>SOA</td>
    <td>{records?.added?.expire}</td>
    <td>{records?.added?.value1} {records?.added?.value2}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)