【发布时间】:2020-06-17 09:40:32
【问题描述】:
我正在制作我的第一个 React-Redux 项目。
我想从 getListAPI 获取数据。
我在 [GET_LIST_SUCCESS] 中检查了 console.log(data),结果就是我想要的。
但console.log(temp) 在容器中,我希望是“数据”,它只是动作对象(仅存在类型)。
如何获取“数据”?
// container
import React from 'react';
import { useDispatch } from 'react-redux';
import Home from 'presentations/Home';
import * as homeActions from 'modules/home';
const HomeContainer = () => {
const dispatch = useDispatch();
const temp = dispatch(homeActions.getList());
console.log(temp);
return (
<Home />
);
}
export default HomeContainer;
// Redux module
import axios from 'axios';
import { call, put, takeEvery } from 'redux-saga/effects';
import { createAction, handleActions } from 'redux-actions';
function getListAPI() {
return axios.get('http://localhost:8000/');
}
const GET_LIST = 'home/GET_LIST';
const GET_LIST_SUCCESS = 'home/GET_LIST_SUCCESS';
const GET_LIST_FAILURE = 'home/GET_LIST_FAILURE';
export const getList = createAction(GET_LIST);
function* getListSaga() {
try {
const response = yield call(getListAPI);
yield put({ type: GET_LIST_SUCCESS, payload: response });
} catch (e) {
yield put({ type: GET_LIST_FAILURE, payload: e });
}
}
const initialState = {
data: {
id: '',
title: '',
created_at: '',
updated_at: '',
content: '',
view: '',
}
};
export function* homeSaga() {
yield takeEvery('home/GET_LIST', getListSaga);
}
export default handleActions(
{
[GET_LIST_SUCCESS]: (state, action) => {
const data = action.payload.data;
console.log(data);
return {
data
};
}
}, initialState
);
也许我需要容器中的 async/await 或 Promise.then() 或 useCallback 等?
因为我以为 Redux-Saga 处理异步,但容器不在 Redux-Saga 区域。
那么我不应该用异步处理注入容器吗?
我写了一些代码进行测试。
期待在几秒钟内收到其他数据。
// container
// const temp = dispatch(homeActions.getList());
let temp = dispatch(homeActions.getList());
let timer = setInterval(() => console.log(temp), 1000);
setTimeout(() => { clearInterval(timer); alert('stop');}, 50000);
没有任何改变。
只是日志动作对象(只存在类型)。
我错过了什么?
【问题讨论】:
-
您的容器有
useDispatch来触发数据获取,但它还需要一个useSelector挂钩才能从redux 存储中获取数据。
标签: reactjs redux redux-saga