我已经看到了一些与此相似的问题,但我不完全确定我是否理解mapDispatchToProps,bindActionCreators和connect如何工作,所以我不确定我哪里出错了。
目前,我正在调用我的recordFullTimeScoreAnswer函数,但是当它进入函数时,返回行后没有任何反应。没有打印console.log,也没有任何错误
组件
renderNextQuestionArrow(question: Question) {
const p = this.props;
const s = this.state;
return (
<div onClick={ () => { p.recordFullTimeScoreAnswer(s.homeScore, s.awayScore, p.question, p.questionIndex, p.user, p.configs) } }>
<Arrow direction="right" action={ () => { p.showNextQuestion() } }/>
</div>
)
}
容器
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { recordFullTimeScoreAnswer, showNextQuestion } from '../actions';
render() {
return(
<FullTimeScoreActive
imgSrc={imgSrc}
user={user}
answerStatus={answerStatus}
question={question}
showNextQuestion={showNextQuestion}
recordFullTimeScoreAnswer={recordFullTimeScoreAnswer}
questionIndex={questionIndex}
total={total}
configs={configs}
/>
)
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ recordFullTimeScoreAnswer, showNextQuestion }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(FullTimeScoreContainer);
export { FullTimeScoreContainer }
动作
export function recordFullTimeScoreAnswer(
homeScore: number,
awayScore: number,
question: Object,
questionIndex: number,
user: User,
configs: Configs
) {
console.log("outside record answer");
return (dispatch: Function) => {
console.log("inside record answer");
let uri = configs.baseAPIPath + '/questions/';
if ( user.loggedIn ) {
fetchWithAuth(uri, 'POST', answer, user.tokens, configs.clientId, dispatch, false, v.questionId).then( (data) => {
if (data) {
dispatch({
type: RECORD_ANSWER_SUCCESS,
payload: { questionIndex, answerId }
})
}
});
}
}
}
我看到的最后一件事是&#34;外部记录答案&#34;记录,但从来没有&#34;内部记录答案&#34;一个
答案 0 :(得分:2)
问题出在这一行:
recordFullTimeScoreAnswer = { recordFullTimeScoreAnswer }
这里你直接传递动作文件中定义的动作,而不是通过mapDispatchToProps
方法传递给props中的组件的动作。在你的情况下,你总是调用外部方法,内部方法永远不会被调用,recordFullTimeScoreAnswer
也无法访问dispatch
。
使用此:
recordFullTimeScoreAnswer={this.props.recordFullTimeScoreAnswer}
注意:强>
如果您这样编写,您编写的方式将打印内部控制台:
recordFullTimeScoreAnswer = {recordFullTimeScoreAnswer()} // notice `()`
但它也会抛出错误。