useEffect 作为具有多个依赖项的组件DidUpdate



如何有条件地更新我的状态?
如果早餐不空,我想更新我的早餐状态,

如果午餐不为空,我想更新我的午餐状态,

如果晚餐不为空,我想更新我的晚餐状态,

如果零食不为空,我想更新我的零食状态,

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { state_breakfast, state_lunch, state_diner, state_snack } from '../../../redux/selectors/meal';
import Card from './Card';
import Buttons from './Buttons';
import isEmpty from '../../common/utils/isEmpty';
const Meals = ({ breakfast, lunch, diner, snack }) => {
const [state, setState] = useState({ Breakfast: false, Lunch: false, Diner: false, Snack: false });
const { Breakfast, Lunch, Diner, Snack } = state;
useEffect(() => {
if(!isEmpty(breakfast)) setState({ ...state, Breakfast: true });
},[breakfast]);
// useEffect(() => {
//   if(!isEmpty(breakfast)) setState({ ...state, Breakfast: true });
//   if(!isEmpty(lunch)) setState({ ...state, Lunch: true });
//   if(!isEmpty(diner)) setState({ ...state, Diner: true });
// },[breakfast, lunch, diner, snack]);
return(
....
)
const mapStateToProps = createStructuredSelector({
breakfast: state_breakfast,
lunch: state_lunch,
diner: state_diner,
snack: state_snack
});
export default connect(mapStateToProps, null)(Meals);

问题是,它的更新只有 1 个状态

欢迎任何帮助, 谢谢

问题是您正在为每个setState重用state

因此,单次传递中的所有更新都会重用当前state并重置同一传递中设置的先前值。

useEffect(() => {
let updates = {};
if (!isEmpty(updateOne)) updates.one = true;
if (!isEmpty(updateTwo)) updates.two = true;
if (!isEmpty(updateTree)) updates.tree = true;
if (!isEmpty(updateFour)) updates.four = true;
setState({
...state,
...updates
});
}, [updateOne, updateTwo, updateTree, updateFour]);

您有 2 个(或更多(选项来实现这一点:

选项 1

单独处理每个状态:

const Meals = ({ breakfast, lunch, diner, snack }) => {
const [breakfast, setBreakfast] = useState(breakfast);
const [lunch, setLunch] = useState(lunch);
const [dinner, setDinner] = useState(diner);
const [snack, setSnack] = useState(snack);
useEffect(() => {
if (breakfast) setBreakfast(true);
if (lunch) setLunch(true);
if (dinner) setDinner(true);
if (snack) setSnack(true);
}, [breakfast, lunch, dinner, snack])

选项 2

function reducer(state, action) {
return { ...state, ...action };
}
const Meals = ({ breakfast, lunch, dinner, snack }) => {
const [state, setState] = useReducer(reducer, { breakfast, lunch, diner, snack });
useEffect(() => {
setState({ breakfast, lunch, dinner, snack });
}, [breakfast, lunch, dinner, snack])

我建议使用useReducer但使用传递更改的函数来处理它。

相关内容

  • 没有找到相关文章

最新更新