React 如何将 props 从 api 传递给组件?
How React pass props from api to component?
我有一个 parentA 和 childB 组件
我想要它单击 parentA 中的一个按钮
然后执行函数从 api 获取数据
然后显示在 B 组件上。这看起来很简单。
parent:
let profileData = {
avatar: '',
first_name: 'hey',
...
};
const handleClickProfileOpen = () => {
setIsProfileOpen(true);
getProfileData();
};
const getProfileData = async() => {
let res;
try {
res = await....;
if (res.code === 200) {
profileData = res.data.data;
...
} else {
...
}
} catch...
};
return (
<>
<UserInfo openProfilePage={ handleClickProfileOpen } />
<Profile profileData={profileData} />
</>
)
child(个人资料)
export default function Profile({profileData}) {
return (
<>
<p>{profileData.first_name}</p>
</>
)}
而我运行它,调用API时profileData不是re-render,last_name总是'hey',
我在 getProfileData 代码中尝试了 setState === 200,但导致错误
Can't perform a React state update on an unmounted component.
我是一个React程序员,如果你回答,我很感激
假设你使用的是函数式组件,你可以使用useState
from react,参考https://reactjs.org/docs/hooks-state.html
例如,
function ParentComponent() {
const [profileData, setProfileData] = useState({
// default value if you needed, otherwise use `null`
avatar: '',
first_name: 'hey',
...
})
const handleClickProfileOpen = () => {
setIsProfileOpen(true);
getProfileData();
};
const getProfileData = async() => {
let res;
try {
res = await....;
if (res.code === 200) {
setProfileData(res.data.data);
...
} else {
...
}
} catch...
};
return (
<>
<UserInfo openProfilePage={ handleClickProfileOpen } />
<Profile profileData={profileData} />
</>
)
}
以上是处理简单react state最简单的方法,当你的state变得更复杂时,你可以找其他的状态管理库。
我有一个 parentA 和 childB 组件 我想要它单击 parentA 中的一个按钮 然后执行函数从 api 获取数据 然后显示在 B 组件上。这看起来很简单。
parent:
let profileData = {
avatar: '',
first_name: 'hey',
...
};
const handleClickProfileOpen = () => {
setIsProfileOpen(true);
getProfileData();
};
const getProfileData = async() => {
let res;
try {
res = await....;
if (res.code === 200) {
profileData = res.data.data;
...
} else {
...
}
} catch...
};
return (
<>
<UserInfo openProfilePage={ handleClickProfileOpen } />
<Profile profileData={profileData} />
</>
)
child(个人资料)
export default function Profile({profileData}) {
return (
<>
<p>{profileData.first_name}</p>
</>
)}
而我运行它,调用API时profileData不是re-render,last_name总是'hey', 我在 getProfileData 代码中尝试了 setState === 200,但导致错误
Can't perform a React state update on an unmounted component.
我是一个React程序员,如果你回答,我很感激
假设你使用的是函数式组件,你可以使用useState
from react,参考https://reactjs.org/docs/hooks-state.html
例如,
function ParentComponent() {
const [profileData, setProfileData] = useState({
// default value if you needed, otherwise use `null`
avatar: '',
first_name: 'hey',
...
})
const handleClickProfileOpen = () => {
setIsProfileOpen(true);
getProfileData();
};
const getProfileData = async() => {
let res;
try {
res = await....;
if (res.code === 200) {
setProfileData(res.data.data);
...
} else {
...
}
} catch...
};
return (
<>
<UserInfo openProfilePage={ handleClickProfileOpen } />
<Profile profileData={profileData} />
</>
)
}
以上是处理简单react state最简单的方法,当你的state变得更复杂时,你可以找其他的状态管理库。