Как изменить компонент реагирования после нажатия на ссылку? - PullRequest
0 голосов
/ 04 апреля 2019
import React, { Component } from 'react';
import {fetchRecipe} from '../actions/recipe.js'
import { connect } from 'react-redux'
import {withRouter} from 'react-router-dom';
import '../css/Recipe.css'

class Recipe extends Component {

    componentDidMount(){
      this.props.fetchRecipe(this.props.recipeId)
    }

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.recipeId !== this.props.recipeId) {
        this.setState({
          recipe_id: this.props.recipeId
        })
      }
    }


    displayRecipeIngredients = (column) => {
      return(
        this.props.recipe.ingredients.map((ingredient, id) => {
          if( id % 3 === column){
            return(
                <li>{ingredient.ingredient.name}, {ingredient.quantity} {ingredient.unit}
                </li>
              )
            }else{
              return null
            }
        })
      )
    }


    render() {
      if(this.props.recipe.recipe){
        return (
        <div className="Recipe">
            <div className="Recipe_card">
            <h2>{this.props.recipe.recipe.name}</h2>
            <div className="Recipe_information">
              <div className="Times">
                <span className="Time Recipe_cooking_time">
                Cooking time: {this.props.recipe.recipe.cooking_time}
                </span>
                <span className="Time Recipe_preparation_time">
                Preparation time: {this.props.recipe.recipe.preparation_time}
                </span>
                <span className="Time Recipe_total_time">
                Total time: {this.props.recipe.recipe.total_recipe_time}
                </span>
              </div>
              <div className = "Recipe_ingredients">
                <span className="Column">
                  <ul>
                    {this.displayRecipeIngredients(0)}
                  </ul>
                </span>
                <span className="Column">
                  <ul>
                    {this.displayRecipeIngredients(1)}
                  </ul>
                </span>
                <span className="Column">
                  <ul>
                    {this.displayRecipeIngredients(2)}
                  </ul>
                </span>
              </div>
            </div>
            <div className="Recipe_process">
              {this.props.recipe.recipe.recipe_process}
            </div>
            </div>
        </div>
        );
      }else{
        return(
          <h2>Loading</h2>
        )
      }
    }
}

const mapStateToProps = (state) => {
    return {
      recipe: state.recipe,
    }
  }

  const mapDispatchToProps = dispatch => {
    return {
      fetchRecipe: (recipe, history) => dispatch(fetchRecipe(recipe, history)),
    }
  }

  export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Recipe));

У меня есть этот реактивный компонент, который я хочу рендерить по разным рецептам.У меня есть какая-то ссылка на маршрутизатор, например, так:

import React, {Component} from 'react'
import {withRouter, Link} from 'react-router-dom';
import "../css/Layout.css"


class SearchResults extends Component{

    render(){
        return (
            this.props.results.map(result => {
            return(
                <Link to={`/recipe/${result.id}`}>
                    <p>
                        {result.name}
                    </p>
                </Link>
            )
        })
        ) 
      }
    }

export default withRouter(SearchResults);

Когда я нажимаю на эти ссылки и получаю любой URL в моем приложении, он доставляет меня туда, куда я хочу, с правильными данными, за исключением случаев, когда я уже наURL, как / рецепт / 2.В этом случае URL-адрес изменяется на правильный номер рецепта (например: / recipe / 9), но приложение не загружает данные рецепта.Я нашел некоторые решения, которые я не смог заставить работать, поэтому я был бы признателен за помощь.

Мои маршруты такие:

import React, { Component } from 'react';
import {BrowserRouter, Route} from 'react-router-dom'
import { connect } from 'react-redux'
import {withRouter} from 'react-router-dom';
import NavigationBar from './components/NavigationBar.js'
import Home from './components/Home.js'
import YourWeek from './components/YourWeek'
import Recipes from './components/Recipes'
import Recipe from './components/Recipe.js'
import Ingredient from './components/Ingredient.js';
import Profile from './components/Profile'
import SignUp from './components/SignUp'
import Login from './components/Login'
import {checkSessionLogin} from './actions/user.js'
import './App.css';


class App extends Component {

  componentDidMount(){
    this.props.checkSessionLogin()
  }

  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <React.Fragment>
          <NavigationBar/>
            <Route exact path="/" component={Home} />
            <Route exact path="/your_week" component={YourWeek} />
            <Route exact path="/recipes" component={Recipes} />
            <Route exact path="/recipe/:id" component={Recipe} />
            <Route exact path="/ingredients" component={Ingredient} />
            <Route exact path="/profile" component={Profile} />
            <Route exact path="/sign_up" component={SignUp} />
            <Route exact path="/login" component={Login} />
          </React.Fragment>
        </BrowserRouter>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    user: state.user
  }
}

const mapDispatchToProps = dispatch => {
  return {
    checkSessionLogin: (user, history) => dispatch(checkSessionLogin(user, history)),
  }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

Спасибо!(Я знаю, что эта проблема очень близка и была решена, но я не заставил ее работать ...) Как я могу повторно обработать компонент React при изменении пути?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...