0
我想使用Redux從操作中獲取數據並顯示我從組件中獲取的API數據獲取的JSON對象的屬性。但是在按照我在互聯網上看到的所有步驟完成後,當我的組件中使用console.log(this.props)時,仍然會得到一個空數組。這個空數組似乎每次使用它時都會添加項目,每次向數組添加「未定義」項目。使用Redux傳遞數據,this.props仍然是空陣列
哦,我action.js
:
import 'whatwg-fetch';
export const FETCH_RECIPES = 'FETCH_RECIPES';
const ROOT_URL = 'http://myapi/recipe/id/';
export function fetchRecipes(id) {
const url = ROOT_URL + id;
return (dispatch) => {
fetch(url)
.then((response) => response.json())
.then((request) => dispatch(fetchRecipesSuccess(request)))
};
}
export function fetchRecipesSuccess(request) {
return {
type: FETCH_RECIPES,
request
};
}
,我輸入我的行動進入減速機,reducer_recipes.js
:
import { FETCH_RECIPES } from "../actions/index";
export function recipes (state = [], action) {
switch(action.type) {
case FETCH_RECIPES:
return [action.request.data, ...state];
default:
return state;
}
}
我createStore: const createStoreWithMiddleware = createStore(rootReducer, applyMiddleware(thunk));
Aaaaand最後,相關的代碼片段來自我的組件:
componentDidMount() {
this.props.fetchData(1);
}
render() {
return (
<h1>{console.log(this.props)}</h1>
)}
function mapStateToProps(state) {
return { recipes: state.recipes };
}
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (id) => dispatch(fetchRecipes(id))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Recipe);
我在哪裏放棄連接this.props?幾個小時後,我一直在嘲笑我的頭。
感謝您的回答,但是這並沒有幫助:(當我行動檢查中,獲取正在經歷和抓取數據,但我猜它是越來越下降在我的減速器或組件中。還有什麼想法? – hejhej123
我明白了,你能告訴我在'action.request.data'中檢索到什麼嗎?如果數據敏感,請屏蔽數據。 –
我終於得到了工作 - 如果我在我的reducer中沒有'.data'使用'action.request',它會顯示數據。我有一個後續問題,雖然我仍然有問題: 在我的組件中,如果我'console.log(this.props.recipes)'我得到一個所有食譜取數組。如果我'console.log(this.props.recipes [0]'我得到這些對象中的一個,其中具有不同的值,如描述,名稱和ID,如果我然後'console.log(this.props.recipes [0] .Name' - 它說名稱是未定義的,儘管我可以看到我的早期console.log中有一個值。可能是什麼原因? – hejhej123