reactjs - '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);
}
}
解决方案
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]);
推荐阅读
- docker - Docker:从子目录复制内容不起作用
- c++ - 如何使用c ++中的字段编号访问protobuf中字段的值
- postgresql - 如何选择与当前用户在所有相同事件中注册的所有用户
- python - 通过装饰器访问父级时,Python将类拆分为多个文件
- javascript - 使用 Angular 9 中的 Keyup 将输入值传递给另一个输入
- javascript - 如何在页面加载时从文件中调用 jquery 函数?
- django - Django(GET) - 是否可以仅在一个参数中传递多个值,而不是多个参数称为相同
- android-studio - 无法找到 Android Studio 的 adb 问题
- python - 提取 YouTube 视频的标题 Python
- kubernetes - 如何在 GKE Ingress 和它转发到的服务之间使用 HTTPS?