问题描述
redux修改state相关组件没有更新
问题出现的环境背景及自己尝试过哪些方法
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
//redux.js
let initState = {
toggle: false,
}
export function counter(state=initState, action) {
let stateCopy = {...state}
switch (action.type) {
case toggle:
stateCopy.toggle?stateCopy.toggle=false:stateCopy.toggle=true;
return stateCopy;
default:
//初始状态
return stateCopy;
}
}
//action creator 创建action
export function toggle() {
return {type:toggle}
}
//index.js
import Siderbar from './pages/layout/sidebar';
import { createStore } from "redux";
import {counter,open,close,toggle} from './redux';
import './App.css';
const store = createStore(counter);
console.log(store.getState(),'store')
ReactDOM.render(
<Router>
<div className='wrapper'>
<div className='siderbar'><Siderbar store={store}/></div>
<div className='main'>
<div className='header'><Header store={store} toggle={toggle}/></div>
<div className='content'>
<Route path='/page1' component={Page1} />
<Route path='/page2' component={Page2} />
</div>
</div>
</div>
</Router>, document.getElementById('root'));
//header.js
import React from 'react';
class Header extends React.Component{
render(){
const store = this.props.store;
const isCollopse = store.getState();
const toggle = this.props.toggle;
console.log(isCollopse,'isCollopse')
console.log(this.props,'this.props')
return(
<div onClick={() => {store.dispatch(toggle());console.log(store.getState().toggle)}}>头部</div>
// <div>头部</div>
);
}
}
export default Header;
//siderbar.js
render() {
const store = this.props.store;
let toggle = store.getState().toggle;
console.log(store.getState(),'111')
return (
<div style={{ maxWidth: 256 }}>
{/* <Button type="primary" onClick={this.toggleCollapsed} style={{ marginBottom: 16 }}>
<Icon type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'} />
</Button> */}
<Menu
defaultSelectedKeys={["1"]}
defaultOpenKeys={["sub1"]}
mode="inline"
theme="dark"
inlineCollapsed={toggle}
>
你期待的结果是什么?实际看到的错误信息又是什么?
期待的结果:点击header改变state的toggle控制siderbar的收缩
错误:state改变了但是siderbar的状态没有更新
react-project 看下这个例子,里面的 focused 跟你的 toggle 是一个意思。