首页 > 解决方案 > 当 redux 状态已通过成功操作更新时,React 组件不刷新

问题描述

React/Redux 组合的新手并尝试解决问题。

当用户第一次访问或登录 / 一个 fetch_user api 请求。目的是页面会根据他们的登录状态以不同的方式显示。在 redux 开发工具中,我可以看到状态正在更新,并且在初始状态之后字段被填充为“auth”,但是,当我在应用程序的子组件中时,该值被视为未定义。如果您需要更多信息,请告诉我。提前致谢。

    // app.js
            const initialState = {};
    const history = createHistory();
    const store = configureStore(initialState, history);

    const MOUNT_NODE = document.getElementById('app');

    const render = messages => {
      ReactDOM.render(
        <Provider store={store}>
          <LanguageProvider messages={messages}>
            <ConnectedRouter history={history}>
              <App />
            </ConnectedRouter>
          </LanguageProvider>
        </Provider>,
        MOUNT_NODE,
      );
    };

    // index.js
            class App extends React.Component {
      componentDidMount() {
        console.log('here');
        this.props.fetchUser();
      }
      render() {
        return (
          <ThemeWrapper>
            <AppContext.Consumer>
          ..... 
        App.propTypes = {
            fetchUser: PropTypes.any.isRequired
        };

   export default withRouter(connect(null, actions)(App));


  import { FETCH_USER } from '../actions/types';

  export default function (state = null, action) {
    switch (action.type) {
      case FETCH_USER:
        console.log('1');
        return action.payload || false;
      default:
        return state;
    }
  }
    // actions
    export const fetchUser = () => async dispatch => {
      const res = await axios.get('/api/current_user');
      // res is the output of the axios request
      dispatch({ type: FETCH_USER, payload: res.data });
    };

// Banner.js - auth = undefined
render() {
    console.log(this.props);
// === auth = undefined. I may be accessing it incorrectly


const mapStateToProps = state => ({
    gradient: state.getIn([reducerUI, 'gradient']),
    chat: state.getIn([chatUI, 'chatSelected']),
    auth: state.auth
  });

  const BannerMaped = connect(
    mapStateToProps,
  )(Banner);

  // configure store

      export default function configureStore(initialState = {}, history) {
        // Create the store with two middlewares
        // 1. sagaMiddleware: Makes redux-sagas work
        // 2. routerMiddleware: Syncs the location/URL path to the state
        const middlewares = [sagaMiddleware, routerMiddleware(history), reduxThunk];

        const enhancers = [applyMiddleware(...middlewares)];

        // If Redux DevTools Extension is installed use it, otherwise use Redux compose
        /* eslint-disable no-underscore-dangle, indent */
        const composeEnhancers =
          process.env.NODE_ENV !== 'production' &&
          typeof window === 'object' &&
          window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
            ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
                // TODO Try to remove when `react-router-redux` is out of beta, LOCATION_CHANGE should not be fired more than once after hot reloading
                // Prevent recomputing reducers for `replaceReducer`
                shouldHotReload: false,
              })
            : compose;
        /* eslint-enable */
        const store = createStore(
          createReducer(),
          fromJS(initialState),
          composeEnhancers(...enhancers),
        );

        // Extensions
        store.runSaga = sagaMiddleware.run;
        store.injectedReducers = {}; // Reducer registry
        store.injectedSagas = {}; // Saga registry

        // Make reducers hot reloadable, see http://mxs.is/googmo
        if (module.hot) {
          module.hot.accept('./reducers', () => {
            store.replaceReducer(createReducer(store.injectedReducers));
          });
        }

        return store;
      }

在此处输入图像描述 在此处输入图像描述

标签: javascriptreactjsredux

解决方案


Redux 存储更新映射到单个组件而不是整个应用程序。

这行意味着,Banner当商店更新时,只有组件会被重新渲染,而不是整个应用程序。

const BannerMaped = connect(
  mapStateToProps,
)(Banner);

所以无论你的Banner组件在哪里,每次fetchUser()响应成功并更新存储时,只有你的Banner组件会被重新渲染。如果您需要重新渲染其他组件,它们也应该使用相应mapStateToProps的 .


推荐阅读