在此应用程序中,我使用redux作为存储,而我面临的问题是无法访问props对象内部的某些值。
这是获取请求的组件:
class SearchBar extends Component {
state = {
locationData:''
}
handleExample = ()=>{
this.props.searchData(this.state.locationData);
}
const mapDispatchToProps = (dispatch)=>{
return{
searchData:(data)=>dispatch(searchData(data))
}
}
export default connect(null, mapDispatchToProps)(SearchBar)
这是动作创建者:
import axios from 'axios'
export const searchData = (data) =>{
return async (dispatch , getState)=>{
//async call
const config = {headers:{'user-
key':'7bd05934d767a3a1edhdh0b782cf7bbdc0'}};
const res = await axios.get(`https://developers.zomato.com/api/v2.1/collections?city_id=2`, config);
//console.log(res.data.collections);
dispatch({
type:'SEARCH_DATA',
data,
payload:res.data
});
}
};
这是减速器:
const initState={
SearchData:[]
}
const dataReducer = (state = initState, action)=>{
switch(action.type){
case 'SEARCH_DATA':
return {
...state,
SearchData:action.payload
}
default:
return state;
}
}
export default dataReducer;
这是生根减少剂
import dataReducer from './dataReducer';
import {combineReducers} from 'redux';
const rootReducer = combineReducers({
data:dataReducer
});
export default rootReducer;
现在我正在尝试将数据分发到该组件的道具中
import React, { Component } from 'react'
import CollectionCard from './CollectionCard'
import {connect} from 'react-redux'
import { searchData } from '../../store/actions/dataActions'
class Collection extends Component {
componentDidUpdate(prevProps){
console.log(this.props.data.searchData)
//console.log(this.state)
}
const mapStateToProps = (state)=>({
data:state.data
})
export default connect(mapStateToProps, )(Collection);
现在,当我从道具访问数据时,我可以访问它直到data选项,这样才能正确获取信息
{SearchData: {…}}
SearchData: {collections: Array(36), has_more: 0, share_url:
"http://www.zoma.to/c-2", display_text: "OR EXPLORE OUR COLLECTIONS",
has_total: 0}
__proto__: Object
但是我无法访问searchData选项,并且似乎无法理解为什么它不起作用。尝试了讨论中以前的一些解决方案,但还是没有运气。