Redux操作未传递到reducer



当用户在文本框中键入内容时,我正试图让文本框更新字数。但是setWordCount操作没有传递给reducer。我不明白为什么这不起作用。

在故障排除过程中,我确认组件正在按预期方式取消初始单词计数状态。我还确认,当用户键入某些内容时,会调用setWordCount。这应该会触发将更新的字数传递给state的操作,但它不会触发。我在控制台中没有收到任何错误,我的中间件记录器也没有启动。

这是我的组件。

import React from 'react';
import { connect } from 'react-redux';
import { setWordCount } from '../../redux/writing/writing.actions';
import { UpdateWordCount, UpdatePercentage } from '../../redux/writing/writing.utils';
import './writing-text-box.styles.scss';
const WritingTextBox = ({wordCount, goal}) => {

var updatedPercentage = UpdatePercentage(wordCount, goal);
var percent = updatedPercentage + '%';

return (
<div className='writing-box-container'>
<textarea className='writing-box' type='text' onChange={
(e) => {
setWordCount(UpdateWordCount(e.target.value));
}
}
/>
<div id='Progress'>
<div id='Bar' style={{width: percent}}></div>
</div>
<p key='writing-box-word-count' className='wordcount' >
{wordCount} / {goal}</p>
</div>
)}
const mapStateToProps = state => ({
wordCount: state.writing.wordCount, 
goal: state.writing.goal, 
percentage: state.writing.percentage
});
const mapDispatchToProps = dispatch => ({
setWordCount: ({wordCount}) => dispatch(setWordCount(wordCount)),
// setPercentage: percentage => dispatch(setPercentage(percentage)),
});
export default connect(mapStateToProps, mapDispatchToProps)(WritingTextBox);

这是我的操作文件,它几乎是从另一个可用的应用程序复制粘贴的:

import WritingTypes from "./writing.types";
export const setWordCount = wordCount => ({
type: WritingTypes.SET_WORD_COUNT,
payload: wordCount,
});

和我的减速器:

import WritingTypes from "./writing.types";
const INITIAL_STATE = {
wordCount: 0, 
goal: 124, 
percentage: 0
}
const writingReducer = (currentState = INITIAL_STATE, action) => {
switch(action.type) {
case WritingTypes.SET_WORD_COUNT: 
return {
...currentState,
wordCount: action.payload
};
default:
return currentState;
}
}
export default writingReducer;

和我的根还原剂:

import { combineReducers } from "redux";
import writingReducer from "./writing/writing.reducer";
const rootReducer = combineReducers ({
writing: writingReducer
})
export default rootReducer;

您需要对命名更加小心。目前,setWordCount是的名称

  1. 动作创建者,它只是创建动作对象。

    export const setWordCount = wordCount => ({
    type: WritingTypes.SET_WORD_COUNT,
    payload: wordCount,
    });
    
  2. 调度动作的道具。

    setWordCount: ({wordCount}) => dispatch(setWordCount(wordCount)),
    

这里应该是第二个:

<textarea className='writing-box' type='text' onChange={
(e) => {
setWordCount(UpdateWordCount(e.target.value));
}
}
/>

为了让它发挥作用,从道具上摧毁它:

const WritingTextBox = ({wordCount, goal,setWordCount}) => {

现在它指向道具,并按预期工作。

相关内容

  • 没有找到相关文章

最新更新