redux存储未更新且组件未还原

时间:2020-03-14 18:17:16

标签: reactjs redux

我对使用redux有疑问。

  1. 我商店中文本的初始状态永远不会初始化,并且始终返回未定义
  2. 组件未通过状态更改重新呈现

function App(props) {
  useEffect(() => {
    console.log(props);
  }, [props]);
  return (
    <div className="App">
      <h1>{props.text && props.text}</h1>
      <button onClick={() => props.setText()}>change</button>
    </div>
  );
}

const mapStateToProps = state => {
  return {
    text: state.text
  };
};

const mapDispatchToProps = dispatch => ({
  setText: () => dispatch(setCurrentText())
});

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

减速器

const initial_state = {
  text: "hello"
};

export const textReducer = (state = initial_state, action) => {
  switch (action.type) {
    case "text-change":
      console.log("in here reducer", action);

      return { ...state, text: action.payload };
    default:
      return state;
  }
};

动作

export const setCurrentText = () => {
  return {
    type: "text-change",
    payload: "change now"
  };
};

1 个答案:

答案 0 :(得分:1)

import {textReducer} from './reducer';

function App(props) {
  useEffect(() => {
    console.log(props);
  }, [props]);
  return (
    <div className="App">
      <h1>{props.text && props.text}</h1>
      <button onClick={() => props.setText()}>change</button>
    </div>
  );
}

const mapStateToProps = state => {
  return {
    text: state.textReducer.text
  };
};

const mapDispatchToProps = dispatch => ({
  setText: () => dispatch(setCurrentText())
});

export default connect(mapStateToProps, mapDispatchToProps)(App); 
相关问题