首页 > 解决方案 > 为什么我创建 Redux-Reducer 时的 state 参数没有更新?

问题描述

帮助,我第一次将 Redux 链接到 React。

我的 state 参数已经传递了值,但是当在switch语句中分配给的值state不是return作为原始值读取时,hello而是在它之后的 return 语句中的No值成为初始值 then ADD

当页面加载时,它显示状态的值为 hello,但是当我发送操作时,状态的值变为“否”

这是我的代码

const MessageReducer = (state = "hello", action) => {
alert(state);
  switch (action.type) {
    case "ADD":
      // state.;
      alert(state);
      return "ADD";
    default:
      return "No";
  }
};
export default MessageReducer;

这是我的配置商店:

import MessageReducer from "../reducers/messageReducer";

export const store = configureStore({
  reducer: { preview: MessageReducer },
});

我的 makdown.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) {
    this.setState({
      current: event.target.value,
    });
    this.props.input(this.state.current);
  }
  render() {
    let i = this.props.messages;
    return (
      <div>
        <form>
          <label for="editor">Enter your text here: </label>
          <textarea
            id="editor"
            name="editor"
            value={this.props.current}
            onChange={this.handleChange}
          ></textarea>
        </form>
        <p id="preview">{i}</p>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    messages: state.preview,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    input: (input) => {
      dispatch(MsgCreator(input));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Markdown);

我的 App.js:

import React from "react";
import Markdown from "./components/markdown";
import "./App.css";

function App(props) {
  return (
    <div className="App">
      <h1>hello world</h1>
      <Markdown />
    </div>
  );
}

export default App;

标签: javascriptreactjsreduxreact-reduxswitch-statement

解决方案


我在任何地方都没有看到 Provider={store}

<Provider store={store}>
<App/>
</Provider>

推荐阅读