我是React的新手,请记住这一点。
我尝试渲染从food2fork API获取的食谱列表,但即使数据被正确提取,我也无法获得更新视图。
这里的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);
这里是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;
}
这里&/reducers/index.js:
import { combineReducers } from 'redux';
import RecipesReducer from "./reducer_recipes";
console.log(RecipesReducer);
const rootReducer = combineReducers({
recipes: RecipesReducer
});
export default rootReducer;
这里&#39; s /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
};
}
我没有收到任何具体错误。该视图不会更新。我试图在文件周围传播一些console.log,试图了解问题所在。 看起来Reducer没有成功地将有效负载传递给组件。
注意:我使用react-promise,因此axios返回的承诺会自动解决。
有什么想法吗?
============================================ =======================
修改
感谢您提供有用的链接,但显然我仍然缺少这些内容。 我修改了动作索引:
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));
});
};
}
我还在商店中加入了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'));
这种行为从以前没有改变过。该视图仍未更新。
注意:如果我在控制台上记录了Reducer中的有效负载,那么数据就在那里。但是当我试图在视图中做同样的事情时,没有任何事情发生。
答案 0 :(得分:0)
您的操作不是同步,您需要使用Async Action将响应传递给reducer,这意味着您必须dispatch
响应而不是返回它。查看给定的链接以获取更多详细信息。
答案 1 :(得分:0)
我会尝试重构你的curl
:
/actions/index.js