我如何渲染从redux-thunk中的响应中获得的数据,并将其放入useEffect中?

9w11ddsr  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(158)

我想从我在redux-thunk中所做的API调用的响应中呈现fullName字符串,并将其放在useEffect中(useDispatch()钩子)。如果我在JSX中没有返回任何内容,并且如果我在console.log中记录它实际传递的状态,我可以在控制台中看到整个数据。但是如果我想呈现数据的任何部分,我会得到一个错误:
未捕获的类型错误:无法读取null的属性(阅读'fullName')。

const Profile = (props) => {
  let { userId } = useParams();

  const dispatch = useDispatch();

  const state = useSelector((state) => state);

  useEffect(() => {
    dispatch(getUserProfile(userId));
  }, []);

  return <div>
    {state.profile.profile.fullName} //error if i want smth to render, two profile because one from redux's initialState, and one from api.
  </div>;
};

export default Profile;

感谢

export const getUserProfile = (userId) => (dispatch) => {
  profileAPI.getProfile(userId).then((response) => {
    debugger
    dispatch(setProfile(response));
  });
};

我尝试了很多条件渲染的方法,但是没有一种方法对我有帮助

rdrgkggo

rdrgkggo1#

你能不能请分享轮廓还原器代码,因为根据我的观察,轮廓就像一个物体

export const initialState = {
    profile:{fullName:""};
}
export const profileReducer =(state = initialState,action={})=>{
..
}

并且您希望仅获取profileReducer数据,则仅按状态获取profileReducer数据。profileReducer并获取const {profile}形式的值

const {profile} = useSelector((state) => state.profileReducer);

对于测试,请检查您是否能够通过以下方式获取proflie数据

useState(()=>{console.log("profile",profile)},[profile])

相关问题