更改商店后,我的组件没有重新呈现。 我通过将他放到控制台来确保商店实际上正在改变 store.subscribe()和console.log(store.getState()),但该组件不会再次呈现。 感谢您的帮助。
configureStore.js
import { createStore, combineReducers } from 'redux';
import home from '../reducers/home';
import favorites from '../reducers/favorites';
export default () => {
const store = createStore(combineReducers({
home,
favorites
}))
return store;
}
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './redux/store/configureStore';
import AppRouter from './router/AppRouter';
const store = configureStore();
const jsx = (
<Provider store={store}>
<AppRouter />
</Provider>
);
ReactDOM.render(jsx, document.querySelector('#root'));
home.js(还原器)
const homeDefaultState = {
name: 'someName'
}
export default (state = homeDefaultState, action) => {
switch (action.type) {
case 'CHANGE_NAME':
return {
...state,
name: 'otherName'
}
default:
return state;
}
}
home.js(操作)
export const changeName = () => ({
type: 'CHANGE_NAME'
})
Home.js(组件)
import React from 'react';
import configureStore from '../../redux/store/configureStore';
import { changeName } from '../../redux/actions/home';
import { connect } from 'react-redux';
const store = configureStore();
const handleName = () => {
store.dispatch(changeName())
}
const Home = (props) => (
<div className="home">
<button onClick={handleName}>
change name
</button>
{props.home.name}
</div>
);
const mapStateToProps = (state) => ({
home: state.home
});
export default connect(mapStateToProps)(Home);
答案 0 :(得分:0)
在Home
组件中,第二次初始化存储。然后将动作绑定到第二家商店
const store = configureStore();
const handleName = () => {
store.dispatch(changeName())
}
与connect()
同时访问App.jsx
中声明的存储
先读后更新。只需移除第二个store
并使用mapDispatchToProps
(second parameter passed至connect()
)即可:
const mapStateToProps = (state) => ({
home: state.home
});
export default connect(mapStateToProps, { handleName: changeName })(Home);