【发布时间】:2019-05-02 16:22:47
【问题描述】:
我的代码有问题,我使用 reactJs 和 redux。
我的错误: TypeError: demo.map 不是函数
我的行动:
// DEMO
export const demoFetchRequest = () => {
return {
type: DEMO_FETCH_REQUEST,
};
};
export const demoFetchSuccess = (demo) => {
return {
type: DEMO_FETCH_SUCCESS,
demo,
};
};
export const demoFetchError = (error) => {
return {
type: DEMO_FETCH_ERROR,
error,
};
};
我的减速机:
const initialState = {
loading: false,
demo: [],
error: null,
};
const demo = (state = initialState, action) => {
switch (action.type) {
case DEMO_FETCH_REQUEST:
return { ...state, loading: true };
case DEMO_FETCH_SUCCESS:
return { ...state, loading: false, demo: action.demo };
case DEMO_FETCH_ERROR:
return { ...state, loading: false, error: action.error };
default:
return state;
}
};
我的数据:
const demoCompletedData = [
{
id: 1,
marketId: "1111-1111-1111-1111",
title: "Autonomous car",
picture: "https://th?id=OIP.fdvfdvfdvfdvfd&pid=Api",
language: "English",
flag: "????????",
completed: true,
date: "22/01/2019 10:30",
rate: 9.1,
categories: {
de: 1,
sp: 2,
uk: 0,
fr: 1,
us: 4,
},
},
{
id: 2,
我的组件DidMount:
componentDidMount() {
this.fetchDemo();
this.fetchUser();
}
我前面的抓取:
fetchDemo() {
this.props.demoFetchRequest();
const { marketId } = this.props.match.params;
axios.get(`/api/v1/passport-authenticate/market/${marketId}`)
.then((res) => { return res.data; })
.then(demo => this.props.demoFetchSuccess(demo))
.catch(error => this.props.demoFetchError(error));
}
我的回报:
const { demo } = this.props;
我的渲染
<h5>{demo.title}</h5>
<p>
Demo
{' '}
{demo.flag}
</p>
{demo.map((el) => {
return (
<div>
{Object.keys(el.categories).map((key) => {
return (
<p>
{key}
:
{el.categories[key]}
</p>
);
})}
</div>
);
})}
当我更改 Object.keys() 时出现另一个错误 TypeError: can't convert undefined to object
{Object.keys(demo).map((el) => {
return (
<div>
{Object.keys(el.categories).map((key) => {
return (
<p>
{key}
:
{el.categories[key]}
</p>
);
})}
</div>
);
})}
你能帮我吗?
【问题讨论】:
-
除了您的问题之外,我认为使用
redux-thunk并将获取逻辑移动到您的动作创建者会更好。您可以在一个函数中触发不同的操作(如 fetchRequest、fetch 本身)。 -
@devserkan 与 thunkMiddleware ?类似于带有 fetch 的 demo.service 和带有 dispatch 的 demo.action 之类的东西?
-
是的,
redux-thunk是redux使用异步操作的中间件,如果您的意思是“thunkMiddleware”的话。 -
啊,如果这些答案解决了您的问题,请不要犹豫,接受您的问题的答案。
-
我不知道你所说的“服务”和“动作”是什么意思,但这里有一个简单的例子来说明你是如何做到的:codesandbox.io/s/yk519xy7px 查找
auth动作。跨度>
标签: javascript reactjs redux