首页 > 解决方案 > 嵌套反应状态使用钩子在 javascript 表达式上返回未定义和未定义

问题描述

我正在处理一个反应项目,当我从状态加载数据时,它会正确加载,但是当我加载嵌套状态或应用 JS 操作时,它返回未定义

这是减速机

export const contributorDetailsReducer = (
  state = { contributor: { contribution: { topUp: [] } } },
  action
) => {
  switch (action.type) {
    case CONTRIBUTOR_DETAILS_REQUEST:
      return { ...state, loading: true };
    case CONTRIBUTOR_DETAILS_SUCCESS:
      return { loading: false, contributor: action.payload };
    case CONTRIBUTOR_DETAILS_FAIL:
      return { loading: false, error: action.payload };
    case CONTRIBUTOR_DETAILS_RESET:
      return { contributor: {} };
    default:
      return state;
  }
};

这是动作

export const contributorListDetails = (id) => async (dispatch) => {
  try {
    dispatch({ type: CONTRIBUTOR_DETAILS_REQUEST });

    const { data } = await axios.get(`/api/v1/customers/${id}`);

    dispatch({
      type: CONTRIBUTOR_DETAILS_SUCCESS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: CONTRIBUTOR_DETAILS_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

这是屏幕代码片段

const ContributorDetailsScreen = ({ history, match }) => {
  const dispatch = useDispatch();

  const contributorDetails = useSelector((state) => state.contributorDetails);
  const { loading, error, contributor } = contributorDetails;

  useEffect(() => {
    dispatch(contributorListDetails(match.params.id));
  }, [dispatch, match]);
  return (
    <>
      <Link className="btn btn-light my-3" to="/all-contributors">
        Go Back
      </Link>
      {loading ? (
        <Loader />
      ) : (
        <Row>
          <Col className="text-center" md={12}>
            <h1>
              {`${contributor.firstName} ${contributor.lastName} ${
                contributor.otherName || ''
              }`}
            </h1>
          </Col>
        </Row>
      )}

这是状态

contributor:
  loading(pin):false
  minor(pin):true
  createdAt(pin):"2020-12-02T14:42:23.140Z"
  _id(pin):"5fc7a826bddf9410360f0caf"
  branch:
    _id(pin):"5fa281e2658a2305c7ffdd76"
    name(pin):"HK Road"
    region(pin): "12"
  firstName(pin):"Emmanuel"

状态

以上工作正常。但是当我尝试到达 branch.name 时,

<p>contributor.branch.name</p>

或者我尝试修改

<p>contributor.firstName.toUpperCase()</p>

我得到错误

×
TypeError: Cannot read property 'toUpperCase' of undefined
ContributorDetailsScreen
src/screens/ContributorDetailsScreen.js:39
  36 | )}
  37 | <Row className="my-3">
  38 |   <Col className="text-center" md={12}>
> 39 |     <h1>
     | ^  40 |       {`${contributor.firstName.toUpperCase()} ${contributor.lastName} ${
  41 |         contributor.otherName || ''
  42 |       }`}{' '}

错误

或者

  26 | ) : (
  27 |   <Row>
  28 |     <Col className="text-center" md={6}>
> 29 |       <h1>{contributor.branch.name}</h1>
     | ^  30 |     </Col>
  31 |     <Col className="text-center" md={6}>
  32 |       <h1>

标签: reactjsreduxreact-reduxreact-hooksstate

解决方案


因为您获取用户(异步),所以您应该等到该值可用后再调用toUpperCase()它。

<Col className="text-center" md={12}>
  <h1>
    // or contributor.firstName && contributor.firstName.toUpperCase()
    {`${contributor.firstName?.toUpperCase()} ${contributor.lastName} ${
      contributor.otherName || ""
    }`}
  </h1>
</Col>;


推荐阅读