Redux不更新商店

时间:2020-08-19 12:29:10

标签: reactjs redux react-redux

我正在学习redux,但在更新商店中的数据时遇到了问题。

b

由于某些原因,import React from "react"; import ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { configureStore } from "@reduxjs/toolkit"; import App from "./App"; const store = configureStore({ reducer: counter }); function counter(state = 0, action) { switch (action.type) { case "INCREMENT": return state + 1; case "DECREMENT": return state - 1; default: return state; } console.log(store.getState()); } function App() { return ( <div> <p>{store.getState()}</p> <button onClick={() => store.dispatch({ type: "INCREMENT" })}> Increment </button> </div> ); } ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root") ); 保持不变,尽管在redux开发工具中进行了可见的更新

Redux dev tools view

Stackblitz:https://stackblitz.com/edit/react-p8vm7h?file=src/index.js

2 个答案:

答案 0 :(得分:0)

因为react不知道商店在变化。 您需要使用react-redux提供的挂钩,该挂钩将组件绑定到redux状态,以便您可以侦听redux状态的变化。

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore } from "redux";
import store from "./App.js";
import App from "./App";


function counter(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(counter);

function App() {
  const counter = useSelector(state => state);
  const dispatch = useDispatch();

  return (
    <div>
      <p>{counter}</p>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>
        Increment
      </button>
    </div>
  );
}
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

答案 1 :(得分:0)

还有另一种选择,我建议您去浏览var mainData = input.payBeneficiaries mainData.map((dta,key) => { let result = mainData.map((parent) => { let children = mainData.filter((child) => { if (child.beneficiaryPayId=== parent.parentBenePayId) { var employees = []; var businessName = dta.beneficiary.businessName employees.push({ "orgHierarchy": businessName }); console.log(employees) } }) }) }) 的基本教程,他们确实需要让Redux知道您的状态。

React