[英]How to pass state as a redux action
我正在尝试找到一种将状态传递给动作或简化器的方法。 例如
我希望能够在操作上运行onDelete
函数,然后更新化onDelete
器上的状态。 但是,为了使其正常工作,我将需要过滤帖子,然后才能删除帖子。
class Posts extends Component {
state = {
posts: [],
loading: true,
}
getPosts = () => {
Axios.get(process.env.REACT_APP_GET_POSTS)
.then( (res) => {
this.setState({
posts: res.data,
loading: false
})
})
// console.log(this.state.posts);
}
componentWillMount(){
this.getPosts();
}
// run this logic on the reducer or on actions.
onDelete = (id) => {
Axios.post(`/api/posts/delete/${id}`);
this.setState({
posts: this.state.posts.filter(post => post.id !== id)
})
}
render() {
const {loading, posts} = this.state;
if (!this.props.isAuthenticated) {
return (<Redirect to='/signIn' />);
}
if(loading){
return "loading..."
}
return (
<div className="App" style={Styles.wrapper}>
<h1> Posts </h1>
<PostList DeletePost={this.onDelete} posts={posts}/>
</div>
);
}
}
这是采取行动的尝试,从技术上讲是可行的。
行动
export const DeletePost = (id) => {
return (dispatch) => {
return Axios.post(`/api/posts/delete/${id}`)
.then( () => {
dispatch({type: DELETE_POST, id});
});
}
}
然后,我们解决了在减速器上实际获得职位的问题。 问题在于,reducer不知道帖子来自何处,它是未定义的。 所以我想知道如何将状态传递给减速器。
并会返回
state.posts.filter不是函数或类似的东西。
reducer.js
import { DELETE_POST} from '../actions/';
const initialState = {
post: [],
postError: null,
posts:[]
}
export default (state = initialState, action) => {
switch (action.type) {
case DELETE_POST:
return ({
...state,
posts: state.posts.filter(post=> post.id !== action.id)
})
default:
return state
}
}
我如何将状态传递给操作,以便能够在reducer上更新状态?
我正在尝试找到一种将状态传递给动作或简化的方法
编写动作代码的方式表明您正在使用redux thunk ,这意味着您可以在动作中访问getState
函数。 getState的示例用法在这里
export const DeletePost = (id) => {
return (dispatch, getState) => {
return Axios.post(`/api/posts/delete/${id}`)
.then( () => {
dispatch({type: DELETE_POST, id});
});
}
}
您已经可以访问化简代码中的状态。 它叫state
!
现在,以上可能结束了答案。 但是我在质疑你在课堂上做什么的前提。
// run this logic on the reducer or on actions.
onDelete = (id) => {
Axios.post(`/api/posts/delete/${id}`);
this.setState({
posts: this.state.posts.filter(post => post.id !== id)
})
}
在上方已过滤/删除redux中的帖子之后,您正在过滤这些帖子(例如,您不必要地过滤了两次)。 相反,您应该直接从redux获取状态
在这里看看。 例如,在更强大的设置中使用此示例。 我将引导您到此示例 。 对于示例,请查看src/containers/visibleTodoList
因此,实际上,对于您正在执行的操作, posts
应仅与redux一起使用,而不应包含在类组件中!
最后,您看到的错误
state.posts.filter不是函数或类似的东西。
您能给出确切的错误吗? 您的减速器代码似乎很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.