【发布时间】:2021-07-12 08:39:18
【问题描述】:
我正在使用 react 和 redux 创建一个系统,我需要从 api 获取一些数据,我创建了 action/function 和 reducer,但是当我尝试访问组件上的结果并控制台记录它们时,它显示未定义三倍于解决,当我尝试映射结果时,我当然不能因为未定义的事情。[在此处输入图像描述][1]
这是我的动作函数代码。
import axios from "axios";
import Cookies from "js-cookie";
export const signIn = () => {
return {
type: 'LOGGED'
};
};
export const getCompaniesAction = (data) => {
return{
type: "GET_COMPANIES",
payload: data
};
};
export function fetchCompanies(){
return(dispatch) => {
return axios.get(`http://ticketing.mydev.loc/api/companies`, {headers:{
Authorization: `Bearer ${Cookies.get('access_token')}`
}}).then(res => res.data.data).then(data => dispatch(getCompaniesAction(data))).catch(err => console.log(err))
}
}
这里是 mu reducer 函数
const companiesReducer = (state = [], action) => {
switch (action.type) {
case 'GET_COMPANIES':
return{
...state,
companies: action.payload
}
default:
return{
...state
}
}
}
export default companiesReducer;
这里是商店
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const store = createStore(
allReducers, compose(applyMiddleware(thunk), composeEnhancer)
)
将状态映射到道具
const mapStateToProps = (state) => ({
companies: state.companiesReducer.companies
})
export default connect(mapStateToProps, actionCreators)(Company);
组件确实挂载了
componentDidMount() {
this.props.fetchCompanies()
}
在这里我尝试访问数据
render(){
if(this.props.companies !== 'undefined'){
console.log(this.props.companies)
}
所以我的 redux devtool 完美地显示了状态变化,但是组件中的这个 console.log 显示 undefined 是显示数据的三倍。 感谢您的宝贵时间
【问题讨论】:
标签: reactjs redux react-redux axios redux-thunk