我是新人,现在就做出反应并选择一门课程。我发现状态在使用异步代码更新方面有点令人困惑。在我正在做的教程中,我发誓说你需要使用thunk来处理使用react / redux更新状态。我对此持怀疑态度,因为我是新人,所以我并非完全理解这一点。我已经编写了这个react组件和reducer,它工作正常,它将更新博客发送到服务器,接收它,并在收到200响应时更新状态,但我想知道是否有它有问题,而不是使用来自http请求的数据更新状态的正确方法。
博客组件
import React, {Component} from 'react';
import axios from '../../http/axios/axios';
import Card from '../../components/UI/Card/Card';
import classes from '../Container.css';
import Button from '../../components/UI/Button/Button';
import * as actionTypes from '../../store/actions/actions';
import { connect } from 'react-redux';
class Blog extends Component{
toggleApprovedAndUpdate = (blog) => {
blog.approved = ! blog.approved
this.props.updateBlog(blog)
}
render() {
let blogs = this.props.blgs.map((b, index) =>
<Card
title={b.title}
description={b.description}
approved={b.approved.toString()}
imagePath={b.image}
action={this.toggleApprovedAndUpdate.bind(this, b)}
key={index} />)
return(
<div>
<div className={classes.Container}>
<Button
label={"Get all blogs"}
action={this.props.getBlogs}
/>
{blogs}
</div>
</div>
)
}
}
const mapStateToProps = state => {
return {blgs: state.blog.blogs};
};
const mapDispatchToProps = dispatch => {
return {
getBlogs: () => {
axios.get('/blog')
.then((response) => {
return dispatch({type: actionTypes.GET_ALL_BLOGS, blogs: response.data})
})
},
updateBlog: (blog) => {
axios.put('/blog', blog)
.then((response) => {
return dispatch({type: actionTypes.UPDATE_BLOG, blogs: response.data})
})
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Blog);
Blog reducer
import * as actionTypes from './actions';
const initialState = {
blogs: []
}
const reducer = (state = initialState, action) => {
switch(action.type){
case actionTypes.GET_ALL_BLOGS:
return {
...state,
blogs: action.blogs
}
case actionTypes.UPDATE_BLOG:
return {
...state,
blogs: state.blogs.map((blog) => blog.id === action.blogs.id ? {...blog, approved:action.blogs.approved}: blog )
}
}
return state;
}
export default reducer;
答案 0 :(得分:0)
我的理解是,您可以像在示例中一样调用异步函数,而无需中间件。像redux-thunk这样的中间件的作用是在调度的动作中添加ID,“排序”它们,避免竞争条件,例如Writing Async Code in redux中描述的竞争条件。