0

I wanted to understand react-redux and I have absolutely no idea why the components are not updated. I think nothing is updated because react doesn't look into the depth of context changes. But even with these thoughts I do not know what to do please help me I'm tired

const MainContext = React.createContext(null);

const createStore = (reducer, initialState) => {
  let currentState = initialState;
  let listeners = [];

  const getState = () => currentState;
  const dispatch = (action) => {
    currentState = reducer(currentState, action);
    listeners.forEach((listener) => listener());
  };

  const subscribe = (listener) => listeners.push(listener);
  return { getState, dispatch, subscribe };
};

I think the error is somewhere here

const useSelector = (selector) => {
  const ctx = React.useContext(MainContext);
  if (!ctx) {
    return 0;
  }
  return selector(ctx.store.getState());
};

const useDispatch = () => {
  const ctx = React.useContext(MainContext);
  if (!ctx) {
    return () => { };
  }
  return ctx.store.dispatch;
};

const Provider = ({ store, context, children }) => {

  const Context = context || MainContext;
  return <Context.Provider value={{ store }}>{children}</Context.Provider>

};

APP

const UPDATE_COUNTER = "UPDATE_COUNTER";
const CHANGE_STEP_SIZE = "CHANGE_STEP_SIZE";

const updateCounter = (value) => ({
  type: UPDATE_COUNTER,
  payload: value,
});
const changeStepSize = (value) => ({
  type: CHANGE_STEP_SIZE,
  payload: value,
});

const defaultState = {
  counter: 1,
  stepSize: 1,
};
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case UPDATE_COUNTER:
      return {
        ...state,
        counter: state.counter + action.payload,
      };
    case CHANGE_STEP_SIZE:
      return {
        ...state,
        stepSize: +action.payload,
      };
    default:
      return state;
  }
};

const Counter = () => {
  const counter = useSelector((state) => state.counter);
  const stepSize = useSelector((state) => state.stepSize);
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch(updateCounter(-stepSize))}>-</button>
      <span> {counter} </span>
      <button onClick={() => dispatch(updateCounter(stepSize))}>+</button>
    </div>
  );
};
const Step = () => {
  const stepSize = useSelector(
    (state) => state.stepSize,
    (current, prev) => current === prev
  );
  const dispatch = useDispatch();

  return (
    <div>
      <div>
        Значение счётчика должно увеличиваться или уменьшаться на заданную
        величину шага
      </div>
      <div>Текущая величина шага: {stepSize}</div>
      <input
        type="range"
        min="1"
        max="5"
        value={stepSize}
        onChange={({ target }) => dispatch(changeStepSize(target.value))}
      />
    </div>
  );
};

ReactDOM.render(
  <Provider store={createStore(reducer, defaultState)}>
    <Step />
    <Counter />
  </Provider>,
  document.getElementById("app")
);

1 Answers1

0

Your useSelector hook is wrongly implemented, because it never subscribes to the store. So, it will never check the state again after it is updated - only when the component happens to re-render for some other reason.

For details on how React-Redux actually works, see my extensive post The History and Implementation of React-Redux and my talk ReactNext 2019: A Deep Dive into React-Redux .

markerikson
  • 63,178
  • 10
  • 141
  • 157