如何清除状态,以使先前状态不会在当前组件中呈现?

时间:2019-04-03 02:48:29

标签: reactjs state react-lifecycle unmount

在我的食谱应用中,当用户单击特定食谱时,它将在组件 recipeById 中呈现所单击食谱的所有详细信息。当我导航回到登录页面并在我的UI中选择另一个食谱时;它首先呈现先前选择的配方的数据,然后重新呈现新选择的配方的数据,我该怎么做以防止出现这种情况?

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);  


2 个答案:

答案 0 :(得分:1)

您需要先清除数据,然后再卸载该组件。

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

然后,在您的RecipeDetail组件中,添加具有声明的操作的componentWillUnmount()

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

在减速器中:

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

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

答案 1 :(得分:0)

什么解决了我的问题:不传递整个状态(即... 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; 
}