如何将道具传递给React子组件? 我收到错误消息:
TypeError: Cannot read property 'user_id' of null
child
D:/T97/React-Test/test/src/child.js:6
3 | const child = (props) => {
4 | const {user} = props;
5 | return (
> 6 | <div className="child">
7 | {user.user_id}
8 | </div>
9 | );
View compiled
当我用user.user_id
替换child.js中的JSON.stringify(user)
时,我得到了:
{"user_id":1,"password":"null","user_name":"User1","email":"user@gmail.com","avatar_url":"https://picsum.photos/300/300"}
API:(“ http:// localhost:5000 / user / 1”)
{"user_id":1,"password":"null","user_name":"User1","email":"user@gmail.com","avatar_url":"https://picsum.photos/300/300"}
App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Child from './child';
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchData = async () => {
const result = await axios.get(
'http://localhost:5000/user/1',
);
setUser(result.data);
};
fetchData();
}, []);
return (
<div className="App">
<Child user={user}/>
</div>
);
}
export default App;
child.js
import React from 'react';
const child = (props) => {
const {user} = props;
return (
<div className="child">
{user.user_id}
</div>
);
};
export default child;
答案 0 :(得分:1)
对于第一个渲染,用户尚不可用(最初为null),在axios请求/响应完成后,用户将可用,并且可以在组件中使用,但是当用户为空:
<div className="child">
{user && user.user_id}
</div>
答案 1 :(得分:0)
在您从API调用获得响应之前,子组件将完成其第一个渲染。在这种情况下,您的子组件将因为此对象的初始状态为null而将其作为null接收到“ user”对象
const [user, setUser] = useState(null);
您可以将初始设置设置为像这样的空对象
const [user, setUser] = useState({});
或者您可以在子组件中添加一个条件
<div className="child">
{user && user.user_id}
</div>
一旦您从API获得响应,用户状态就会更新,您将获得所需的输出。
这是有效的示例https://stackblitz.com/edit/react-eutbvw?file=src%2FApp.js