javascript - 当 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;
}
解决方案
Redux 存储更新映射到单个组件而不是整个应用程序。
这行意味着,Banner
当商店更新时,只有组件会被重新渲染,而不是整个应用程序。
const BannerMaped = connect(
mapStateToProps,
)(Banner);
所以无论你的Banner
组件在哪里,每次fetchUser()
响应成功并更新存储时,只有你的Banner
组件会被重新渲染。如果您需要重新渲染其他组件,它们也应该使用相应mapStateToProps
的 .
推荐阅读
- c# - 计算 Windows 窗体的边界框
- python - 如何在 django 模板中将 base64 变量转换为纯数字?
- python - python中的矩阵乘法 - 创建结果的问题
- php - 使用 ajax 在引导模式中动态显示内容无法正常工作
- css - Safari 在变换旋转时显示 2 个图标
- python - 熊猫数据透视表转换为默认字典(列表)
- azure - azure 函数可以使用应用程序 SSO 令牌进行身份验证吗?
- python - 如何解决 Python 数据框箱线图列错误
- netsuite - Netsuite - 保存的搜索公式(文本)案例语句连接 2 个字段
- sql - 具有额外列名的动态数据透视表