gpt4 book ai didi

javascript - 如何将状态作为 redux 操作传递

转载 作者:行者123 更新时间:2023-11-30 14:04:44 24 4
gpt4 key购买 nike

我正在尝试找到一种将状态传递给 Action 或缩减器的方法。例如

我希望能够在操作上运行 onDelete 函数,然后更新 reducer 上的状态。但是,为了使其工作,我需要过滤帖子然后我才能删除帖子。

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>
);
}
}

这里是将尝试变成一个 Action ,在技术上是可行的。

Action

export const DeletePost =  (id) => { 
return (dispatch) => {
return Axios.post(`/api/posts/delete/${id}`)
.then( () => {
dispatch({type: DELETE_POST, id});
});
}
}

然后我们处理实际获取 reducer 上的帖子的问题。问题是 reducer 不知道帖子来自哪里,它是未定义的。所以我想知道如何将状态传递给 reducer 。

会回来

state.posts.filter is not a function or something along those lines.

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 上的状态?

最佳答案

I'm trying to find a way to pass a state to an action or a reduce

您编写操作代码的方式表明您正在使用 redux thunk ,这意味着您可以在操作中访问 getState 函数。 getState 的用法示例是 here

export const DeletePost =  (id) => { 
return (dispatch, getState) => {
return Axios.post(`/api/posts/delete/${id}`)
.then( () => {
dispatch({type: DELETE_POST, id});
});
}
}

您已经可以访问 reducer 代码中的状态。它叫做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 获取状态

看看here .例如,在更强大的环境中使用它。我会引导你到这个example .例如,查看 src/containers/visibleTodoList

所以对于你正在做的事情来说,posts 应该只存在于 redux 而不是类组件中!


最后是你看到的错误

state.posts.filter is not a function or something along those lines.

你能给出确切的错误吗?你的 reducer 代码看起来不错。

关于javascript - 如何将状态作为 redux 操作传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com