如何清除状态,使之前的状态不在当前组件中呈现?

How to clear the state so that the previous state doesn't render in the current component?

在我的菜谱应用中,当用户点击特定菜谱时,它会在组件 recipeById 中呈现所点击菜谱的所有详细信息。当我导航回登录页面时,select 另一个食谱,在我的 UI 中;它首先呈现之前 selected 配方的数据并重新呈现新 selected 配方的数据,我应该怎么做才能防止它???

recipeReducer.js

import { GET_RECIPES, GET_RECIPE_BY_ID} from "../actions/types.js"; 
const initialState = { 
      recipes: [],
      recipe:{}
};

export default function (state = initialState, action) { 
    switch(action.type) {
        case GET_RECIPES:
             return {
                     ...state,  
                     recipes:action.payload
                    }; 
        case GET_RECIPE_BY_ID:
             return {
                     ...state,  
                     recipe:action.payload
                    }; 
        default:
             return state; 
}

recipeActions.js

import { GET_RECIPES, GET_RECIPE_BY_ID} from "./types.js"; 
import axios from 'axios'; 

export const getRecipes = () =>async dispatch => { ... }
export const getRecipeById = (id) =>async dispatch => { 
     const res = await axios.get(`/api/recipe/${id})
     dispatch({
           type:GET_RECIPE_BY_ID,
           payload: res.data
     }); 
}

recipeById.js

import React, {component} from 'react'; 
import {connect} from 'react-redux'; 
import {getRecipeById} from '../../actions/recipeActions.js'; 
import RecipeCard from './RecipeCard'; 

class RecipeById extends Component {
    constructor(props) {
       super(props); 
     } 

  componentDidMount = async() => {
    this.props.getRecipeById(this.props.match.params.id);    
  }

  render() {
     return(
         <RecipeCard 
           title={recipe.title}
           description={recipe.description}
           image= {recipe.image}
          />
     )
  }
}
const mapStateToProps = state => ({
       recipes: state.recipe.recipes,
       recipe: state.recipe.recipe
}); 
export default connect(mapStateToProps, {getRecipeById})(RecipeById);  


卸载该组件前需要清除数据。

为此,创建另一个操作(例如:clearData

然后,在您的 RecipeDetail 组件中,添加一个 componentWillUnmount(),其中包含已声明的操作:

componentWillUnmount() { 
  this.props.clearData();
}

在你的减速器中:

case CLEAR_DATA: 
  return {
    ...state,
    recipe: {}
  }

因此,在您返回列表页面之前,详细信息页面中的数据将被清除。

解决我的问题的方法:不传递整个状态(即 ...state ),而是只传递组件需要的东西....

import { GET_RECIPES, GET_RECIPE_BY_ID} from "../actions/types.js"; 
const initialState = { 
      recipes: [],
      recipe:{}
};

export default function (state = initialState, action) { 
    switch(action.type) {
        case GET_RECIPES:
             return {
                      //...state
                     recipes:action.payload
                    }; 
        case GET_RECIPE_BY_ID:
             return {
                     //...state
                     recipe:action.payload
                    }; 
        default:
             return state; 
}