为什么创建Redux Reducer时传入的state参数未按预期更新?
问题根因
- Reducer默认分支逻辑错误:Redux规范要求Reducer在命中不匹配的action类型时,必须返回当前传入的state值。你当前的代码在default分支写死返回固定值
No,只要触发的action类型不是ADD,原有state就会被强制覆盖为No,初始的hello值自然丢失。 - Action类型不匹配:你触发的action由
MsgCreator(input)生成,若该action creator返回的type字段不是字符串ADD,就会始终走default分支,无法命中ADD的逻辑。 - setState异步导致传值错误:
setState是异步更新API,调用后立刻读取this.state.current拿到的是更新前的旧值,无法获取当前输入的最新内容。 - textarea绑定错误:你给textarea的
value属性绑定了this.props.current,但mapStateToProps和父组件都没有传递该属性,导致textarea变成非受控组件,输入内容无法同步。
修复方案
1. 修复MessageReducer
const MessageReducer = (state = "hello", action) => { switch (action.type) { case "ADD": // 取action携带的输入内容作为新state返回,可按需调整逻辑 return action.payload; default: // 不匹配的action直接返回原有state return state; } }; export default MessageReducer;
2. 检查msgAction.js的action creator定义
确保返回的type为ADD,示例:
const MsgCreator = (inputContent) => { return { type: "ADD", payload: inputContent } } export default MsgCreator;
3. 修复markdown.js组件逻辑
import React from "react"; import { connect } from "react-redux"; import MsgCreator from "../actions/msgAction"; class Markdown extends React.Component { constructor(props) { super(props); this.state = { current: "", }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { const newValue = event.target.value; this.setState({ current: newValue, }); // 直接用最新的输入值dispatch,避免读取异步更新的state旧值 this.props.input(newValue); } render() { return ( <div> <form> <label htmlFor="editor">Enter your text here: </label> <textarea id="editor" name="editor" {/* 绑定组件内部state的current值 */} value={this.state.current} onChange={this.handleChange} ></textarea> </form> <p id="preview">{this.props.messages}</p> </div> ); } } const mapStateToProps = (state) => { return { messages: state.preview, }; }; const mapDispatchToProps = (dispatch) => { return { input: (input) => { dispatch(MsgCreator(input)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(Markdown);
内容的提问来源于stack exchange,提问作者Yagi91
相关产品推荐
相关产品推荐

