0

在我的食谱应用程序中,当用户点击特定食谱时,它会在组件recipeById中呈现点击食谱的所有详细信息。当我导航回登录页面并在我的 UI 中选择另一个食谱时;它先渲染了之前选择的recipe的数据,然后重新渲染了新选择的recipe的数据,应该怎么做才能防止呢???

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


4

2 回答 2

1

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

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

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

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

在你的减速器中:

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

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

于 2019-04-03T02:57:37.443 回答
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; 
}
于 2019-04-03T14:25:34.037 回答