useEffect作为具有多个依赖项的componentDidUpdate

时间:2019-11-22 18:55:39

标签: reactjs react-hooks

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

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

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

如果小吃不为空,我想更新我的小吃状态,

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个状态

欢迎任何帮助, 谢谢

2 个答案:

答案 0 :(得分:1)

问题是您为每个state重新使用setState

因此,一次通过中的所有更新将重新使用当前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]);

答案 1 :(得分:1)

您有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,但通过传递更改的函数来处理它。