首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用redux store.subscribe运行React功能组件

使用redux store.subscribe运行React功能组件
EN

Stack Overflow用户
提问于 2021-03-12 00:18:38
回答 1查看 347关注 0票数 1

考虑下面在react中编写的代码(也包括redux)

代码语言:javascript
运行
复制
store = createStore(todoApp) ;
store.subscribe(App);

export default function App(){
  .....
}

这意味着对于我的App函数组件中发生的每个分派操作,App都必须呈现,因为subscribe会执行包含的函数。然而,我观察到的是,尽管该函数会执行,但HTML组件不会从第一次呈现时更新并保持不变,即使在多次调度操作之后也是如此。有人能解释这种行为吗?

EN

回答 1

Stack Overflow用户

发布于 2021-03-12 02:16:18

这不是将React应用程序连接到redux存储的方式。下面是一个使用Provider和react-redux挂钩的示例应用程序:

代码语言:javascript
运行
复制
//you would import these with
//  import {Provider} from 'react-redux'
const { Provider, useDispatch, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const { createSelector } = Reselect;
const { memo, useMemo, useCallback } = React;

const initialState = {
  counters: [
    { id: 1, count: 1 },
    { id: 2, count: 1 },
    { id: 3, count: 1 },
  ],
};
//action types
const ADD = 'ADD';
//action creators
const add = (id) => ({
  type: ADD,
  payload: id,
});
const reducer = (state, { type, payload }) => {
  if (type === ADD) {
    return {
      ...state, //not needed in this case but usually is
      counters: state.counters.map(
        (counter) =>
          counter.id === payload
            ? { ...counter, count: counter.count + 1 }
            : counter //do not update this counter (not the right id)
      ),
    };
  }
  return state;
};
//selectors
const selectCounters = (state) => state.counters;
const createSelectCounterById = (counterId) =>
  createSelector(
    [selectCounters], //re use select counters
    (
      counters //got the counters, find the right counter
    ) => counters.find(({ id }) => id === counterId)
  );
//select sum of all counters
const selectSum = createSelector(
  [selectCounters], //re use select counters
  (counters) =>
    //reduce counters array to a number
    counters.reduce(
      (result, counter) => result + counter.count,
      0
    )
);
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(() => (next) => (action) =>
      next(action)
    )
  )
);
const Counter = memo(function Counter({ id, addAction }) {
  const selectCounter = useMemo(
    () => createSelectCounterById(id),
    [id]
  );
  const counter = useSelector(selectCounter);
  return (
    <li>
      {counter.count}
      <button onClick={() => addAction(id)}>+</button>
    </li>
  );
});
const Total = memo(function Total() {
  const sum = useSelector(selectSum);
  return <h3>{sum}</h3>;
});
const App = () => {
  const counters = useSelector(selectCounters);
  const dispatch = useDispatch();
  const addAction = useCallback(
    (id) => dispatch(add(id)),
    //dispatch is not really a dependency but
    //  linter doesn't know that and adding
    //  it doesn't change behavior
    [dispatch]
  );
  return (
    <div>
      <Total />
      <ul>
        {counters.map(({ id }) => (
          //id property here is not html id element property
          <Counter key={id} id={id} addAction={addAction} />
        ))}
      </ul>
    </div>
  );
};

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>
<div id="root"></div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66586379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档