【发布时间】:2018-07-15 11:28:31
【问题描述】:
我想在 react-redux 中写一个 CRUD,并且有多个调度的问题。我认为我的调度没有返回承诺?
我的错误是“Uncaught TypeError: dispatch(...).then is not a function”,在这一行:
fetchPost: (id) => {
dispatch(fetchPost(id))
.then((result) => ...
动作
export function fetchPost(id) {
const request = axios.get(`${ROOT_URL}/posts/details/${id}`);
console.log(request);
return {
type: "FETCH_POST",
payload: request
}
}
export function fetchPostSuccess(post) {
return{
type: "FETCH_POST_SUCCESS",
payload: post
}
}
export function fetchPostError(error) {
return{
type: "FETCH_POST_ERROR",
payload: error
}
}
减速器
case "FETCH_POST":
return {
...state,
loading: true,
activePost: state.activePost
}
case "FETCH_POST_SUCCESS":
return {
...state,
activePost: action.payload
}
case "FETCH_POST_ERROR":
return {
...state,
activePost: []
}
组件
class Details extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
this.props.fetchPost(this.props.detail_id.id);
}
render() {
return (
<div>
Details page
<ul>
<li >
{this.props.detail_id.id}
</li>
</ul>
</div>
)
}
}
容器
const mapStateToProps = (state, ownProps) => ({
posts: state.posts,
});
const mapDispatchToProps = dispatch => {
return {
fetchPost: (id) => {
dispatch(fetchPost(id))
.then((result) => {
if (result.payload.response && result.payload.response.status !== 200){
dispatch(fetchPostError(result.payload.response.data));
} else {
dispatch(fetchPostSuccess(result.payload.data));
}
})
},
resetMe: () => {
console.log('reset me');
}
};
};
const GetDetails = connect(
mapStateToProps,
mapDispatchToProps
)(Details)
我只想从帖子列表中挑选帖子并在另一个页面上显示详细信息...希望有人帮助我解决此问题
传奇
export function* fetchProducts() {
try {
console.log('saga')
const posts = yield call(api_fetchPost);
console.log(posts);
yield put({ type: "FETCH_SUCCESS", posts});
} catch (e) {
yield put({ type: "FETCH_FAILD", e});
return;
}
}
export function* watchFetchProducts() {
yield takeEvery("FETCH_POSTS", fetchProducts)
}
【问题讨论】:
-
fetchPost(id)正在返回一个动作而不是承诺。我建议,要使用异步操作,请查看 redux-thunk 或 redux-saga。 -
我正在使用 redux saga 加载一个 json 文件
标签: javascript reactjs react-redux