首页 > 解决方案 > 'useEffect' 不只运行一次

问题描述


谢谢大家,尤其是 Mr.Drew Reese。如果您像我一样是新手,请参阅他的答案


我不知道为什么,但是当我使用useEffect控制台记录状态数据时,它总是会重新呈现,尽管状态generalInfo没有改变:/ 所以有人可以帮助我修复它并解释我的错误吗?

我想要的结果是数据将在generalInfo更改时更新。

非常感谢!

这是我的useEffect

========================问题在这里:

  const {onGetGeneralInfo, generalInfo} = props;
  const [data, setData] = useState(generalInfo);

  useEffect(() => {
    onGetGeneralInfo();
    setData(generalInfo);
  }, [generalInfo]);

=========================修复:

 useEffect(() => {
    onGetGeneralInfo();
  }, []);

  useEffect(() => {
    setData(generalInfo);
  }, [generalInfo, setData]); 

这是mapStateToProps

const mapStateToProps = state => {
  const {general} = state;
  return {
    generalInfo: general.generalInfo,
  };
};

这是mapDispatchToProps

const mapDispatchToProps = dispatch => {
  return {
    onGetGeneralInfo: bindActionCreators(getGeneralInfo, dispatch),
  };
};

这是减速机

case GET_GENERAL_INFO_SUCCESS: {
        const {payload} = action;
        return {
          ...state,
          generalInfo: payload,
        };
      }

这是行动

export function getGeneralInfo(data) {
  return {
    type: GET_GENERAL_INFO,
    payload: data,
  };
}
export function getGeneralInfoSuccess(data) {
  return {
    type: GET_GENERAL_INFO_SUCCESS,
    payload: data,
  };
}
export function getGeneralInfoFail(data) {
  return {
    type: GET_GENERAL_INFO_FAIL,
    payload: data,
  };
}

这是传奇

export function* getGeneralInfoSaga() {
  try {
    const tokenKey = yield AsyncStorage.getItem('tokenKey');
    const userId = yield AsyncStorage.getItem('userId');
    const params = {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${tokenKey}`,
      },
    };

    const response = yield call(
      fetch,
      `${API_GET_GENERAL_INFO}?id=${userId}`,
      params,
    );
    const body = yield call([response, response.json]);

    if (response.status === 200) {
      yield put(getGeneralInfoSuccess(body));
    } else {
      yield put(getGeneralInfoFail());
      throw new Error(response);
    }
  } catch (error) {
    yield put(getGeneralInfoFail());
    console.log(error);
  }
}

标签: reactjsreduxreact-reduxreact-hooksredux-saga

解决方案


redux 中的初始状态和组件中的状态是一个空数组。所以我想从 API 获取数据。我把它推到redux的状态。然后我用状态它。我想使用 useEffect 因为我想在 PUT 数据时更新状态并在更新后更新本地状态。

好的,所以我收集到您希望在组件挂载时获取数据,然后在填充时将获取的数据存储到本地状态。为此,您需要将关注点分离到单独的效果挂钩中。一个在组件挂载时分派一次数据获取,另一个“监听” redux 状态的变化以更新本地状态。请注意,将传递的道具存储在本地状态中通常被认为是反模式。

const {onGetGeneralInfo, generalInfo} = props;
const [data, setData] = useState(generalInfo);

// fetch data on mount
useEffect(() => {
  onGetGeneralInfo();
}, []);

// Update local state when `generalInfo` updates.
useEffect(() => {
  setData(generalInfo);
}, [generalInfo, setData]);

推荐阅读