实际上,我仍然对嵌套组件中的Dispatch感到困惑。我知道在redux中,我们可以在任何级别使用调度。
首先,我有如下所示的减速器:
var defaultCommentState = {
login_status: false,
author_name: '',
author_email: '',
author_url: 'https://google.com',
content: '',
post:null,
parent:0
}
const addComment = (state = defaultCommentState, action) => {
switch(action.type) {
case 'ADD_COMMENT':
return {
...state,
login_status: action.login_status,
author_name: action.author_name,
author_email: action.author_email,
content: action.content,
postid: action.postid,
parentid: action.parentid
}
default:
return state;
}
}
export default addComment;
我有一个组件是Comment List
,在这里我可以知道postid
通过postid添加与该帖子相对应的Comment Form
。
class CommentList extends Component {
constructor(props) {
super(props);
//In this component I can get postid like this.
//I want to send this `postid` to store for using in another component.
//How can I use Dispatch in this situation.
var {postid} = this.props;
this.state = {
comments: [],
page: 1,
loadedDone: false,
error: null,
}
}
....
....
}
withRouter(CommentList)
如何在组件中使用Redux Dispatch。 很抱歉,因为我是Redux的新手,我尝试过但没有运气。
非常感谢
答案 0 :(得分:2)
您应该具有this.props.dispatch,如果没有,您很可能忘记了使用Provider包装您的应用程序(来自“ redux-form”包)
您的组件应如下所示:
要使用您应该导入的操作
import myAction from './my-reducer';
那么您应该具有调用该动作的函数
invokeAction() {
const { dispath } = this.props;
dispatch(myAction());
}
编辑:
import { Component } from 'react';
import { connect } from 'react-redux';
import { myAction } from './my-action';
class Test extends Component {
render() {
const { doSomething} = this.props;
return <button onClick={ () => doSomething() } / >
}
}
export default connect(
() => ({}), // Map state to props
dispatch => ({ doSomething: () => dispatch(myAction()) })
)(Test);