简体   繁体   English

React Redux-从reducer传递数据时容器/组件未更新

[英]React Redux - container/component not updating when passing data from reducer

I'm new to React, please keep this in mind. 我是React的新手,请记住这一点。

I'm trying to render a list of recipes fetched from food2fork API but I can't get the view to update, even if the data is fetched correctly. 我正在尝试呈现从food2fork API获取的食谱列表,但是即使数据正确获取,我也无法更新视图。

Here's recipe_list.js: 这是recipe_list.js:

import React, { Component } from "react";
import { connect } from "react-redux";

    class RecipesList extends Component {
    // renderRecipe(recipe) {
    //     console.log(recipe);
    //     return (
    //         <div>{recipe}</div>
    //     );
    // }

    render() {
        console.log("Render function ", this.props.recipes)
            return (
            <div>
                <p>Recipes</p>
                <div>{this.props.recipes}</div>
            </div>
            );
    }
}

function mapStateToProps(state){
    return { recipes: state.recipes };
}

export default connect(mapStateToProps)(RecipesList);

Here's reducer_recipes.js: 这是reducer_recipes.js:

import FETCH_RECIPES from "../actions/index";

export default function(state = [], action){
    switch (action.type) {
        case FETCH_RECIPES:
            return action.payload;
    }
    return state;
}

Here's /reducers/index.js: 这是/reducers/index.js:

import { combineReducers } from 'redux';
import RecipesReducer from "./reducer_recipes";

console.log(RecipesReducer);
const rootReducer = combineReducers({
  recipes: RecipesReducer
});

export default rootReducer;

Here's /actions/index.js: 这是/actions/index.js:

import axios from "axios";

const API_KEY = "****************************";
export const URL = `https://food2fork.com/api/search?key=${API_KEY}`;


export const FETCH_RECIPES = "FETCH_RECIPES";

export function fetchRecipes(term){
    const url = `${URL}&q=${term}`;
    const request = axios.get(url);

    return {
        type: FETCH_RECIPES,
        payload: request
    };
}

I don't get any specific error. 我没有任何特定的错误。 The view just doesn't update. 视图只是不更新​​。 I tried to spread some console.log around the files to try to understand where the problem is. 我试图在文件中散布一些console.log,以了解问题出在哪里。 It seems like the Reducer is not successfully delivering the payload to the component. 减速器似乎没有成功将有效负载交付给组件。

NOTE: I'm using react-promise so the promise returned from axios is automatically resolved. 注意:我使用的是react-promise,所以axios返回的promise将自动解决。

Any ideas? 有任何想法吗?

=================================================================== ================================================== =================

EDIT: 编辑:

Thank you for the useful links but there is clearly something that I'm still missing here. 感谢您提供有用的链接,但显然这里仍然缺少某些内容。 I have modified the action index: 我修改了动作索引:

function getStuffSuccess(response) {
  return {
    type: FETCH_RECIPES,
    payload: response
  };
}

function getStuffError(err) {
  return {
    type: ERROR_FETCH_RECIPES,
    payload: err
  };
}

export function fetchRecipes(term) {
    const url = `${URL}&q=${term}`;

  return function(dispatch) {
    axios.get(url)
      .then((response) => {
        dispatch(getStuffSuccess(response));
      })
      .catch((err) => {
        dispatch(getStuffError(err));
      });
  };
}

I have also included redux-thunk to the store: 我也将redux-thunk包括在商店中:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from "redux-promise";
import Thunk from 'redux-thunk';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(Thunk, ReduxPromise)    (createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('.container'));

The behaviour hasn't changed from before. 行为没有改变。 The view is still not updating. 该视图仍未更新。

NOTE: If I console.log the payload from the Reducer the data is in there. 注意:如果我用console.log从Reducer记录有效负载,则数据就在那里。 But when I try to do the same in the View nothing happens. 但是,当我尝试在“视图”中执行相同操作时,什么也没有发生。

Your action is not synchronus here, you need to use Async Action to deliver the response to reducer, meaning, you have to dispatch the response instead of returning it. 您的操作在这里不是同步的,您需要使用异步操作将响应传递给reducer,这意味着您必须dispatch响应而不是返回响应。 Check the given link for more details. 检查给定的链接以获取更多详细信息。

I would try refactoring your /actions/index.js like so: 我会尝试像这样重构您的/actions/index.js

import axios from 'axios';

export const FETCH_RECIPES = 'fetch_recipes';
export const CREATE_RECIPE = 'create_recipe';

const ROOT_URL = '<url-of-api-endpoint>';
const API_KEY = '<api-key>';

export function fetchRecipes() {
  const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);

  return {
    type: FETCH_RECIPES,
    payload: request
  };
}

export function createRecipe(values, callback){
  const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, values)
  .then(() => callback());

  return {
    type: CREATE_RECIPE,
    payload: request
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM