1.问题如下:随便在一个js工具类里面获取store之后,再store.dispatch(actions),改变了状态后页面无法自动更新?只能在用页面组件connect自动注入到props里面的dispatch改变的状态才能自动更新页面?
2.代码如下
Home 页面组件:
class Home extends Component{
constructor(props){
super(props);
this.goUser = this.goUser.bind(this)
}
goUser() {
let {dispatch} = this.props;
// 通过注入的dispatch对象调用就正常,能触发页面自动更新
**dispatch(setDialogState({showDialog: true}));**
// 通过工具类就不
> 引用文字
行,状态改变后无法触发页面更新
**utils.setDialogState({showDialog: true});**
this.props.history.push('/user')
}
render() {
return (
<div>
<h3>home</h3>
<button onClick={this.goUser}>去用户中心页面</button>
</div>
)
}
}
export default connect()(Home);
utils.js文件如下:
import storeConfigure from '../store';
import {setDialogState} from '../actions';
const appStore = storeConfigure()
export default {
setDialogState: function(data){
appStore.dispatch(setDialogState(data))
}
}
user.js页面组件
import React,{Component} from 'react';
import Dialog from './Dialog';
import { connect } from 'react-redux'
class User extends Component{
constructor(props){
super(props);
}
componentWillMount() {
alert('componentWillMount user')
}
componentWillReceiveProps(nextProps){
alert('componentWillReceiveProps user')
}
render() {
return (
<div>
<h3>user</h3>
<Dialog show={this.props.showDialog}/>
</div>
)
}
}
const mapStateToProps = function(state) {
return {
showDialog: state.app.showDialog
}
}
export default connect(mapStateToProps)(User);
reducers文件夹下的app分块的js内容如下
import * as types from '../actions/actionType'
let initialState = {
showDialog: false
}
export function app(state=initialState,action){
switch(action.type){
case types.SET_DIALOG_STATE:
return Object.assign({},initialState,action.data);
break;
default :
return Object.assign({},initialState,action.data);
break;
}
}
store.js如下:
import {createStore} from 'redux';
import reducers from '../reducers';
export default function configureStore(initialState) {
let store = createStore(reducers, initialState,
// 触发 redux-devtools
window.devToolsExtension ? window.devToolsExtension() : undefined
);
return store;
}