在我的食谱应用程序中,当用户点击特定食谱时,它会在组件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);