繁体   English   中英

我如何呈现从我在 redux-thunk 中所做的响应中获得的数据并将其放入 useEffect 中?

[英]How can I render the data that I got from the response that I did in redux-thunk and put it in useEffect?

我想从我在 redux-thunk 中执行的 API 调用的响应中呈现 fullName 字符串,并将其放入带有调度的 useEffect 中(useDispatch() 挂钩)。 如果我在 JSX 中什么都不返回,并且如果我 console.log state 它实际上是通过了,我可以在控制台中看到整个数据。 但是如果我想渲染数据的任何部分,我会得到一个错误:

未捕获的类型错误:无法读取 null 的属性(读取“全名”)。

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));
  });
};

我尝试了条件渲染,但没有找到解决方案。 我尝试了很多条件渲染的方法,但没有一种有帮助

你能不能也请分享 Profile Reducer 代码,因为根据我的观察,Profile 就像一个 object

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

并且您只想获取 profileReducer 数据,然后通过 state.profileReducer 仅获取 profileReducer 数据,并将值作为 const {profile}

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

用于测试检查您是否能够通过以下方式获取配置文件数据

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM