我已经和React玩了一段时间,并试图尽可能地避免Redux的头痛。现在我正在开发一个使用Redux并需要帮助的项目。
我认为侧边栏是打开和关闭的,因为我认为这是一项轻松的任务,但这是我所做的混乱:
MenuSide.js
import React from 'react';
import { connect } from 'react-redux';
import './MenuSide.scss';
import data from './MenuData';
import toggleVisibility from './MenuSideActions';
import Accordion from '../Accordion/Accordion';
class MenuSide extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.dispatch(toggleVisibility());
}
render() {
return (
<div className="sidebar-container">
<div className={this.props.visible ? 'sidebar large-3 columns' : 'hide' }>
<div className={this.props.visible ? 'button-open' : 'hide'} onClick={() => {
this.handleClick()
}}>
</div>
<div className="sidebar-header">
<h3 className="id-header-text">8374995867</h3>
{ /*optional message*/ }
{ data.messsage ? <h5>data.message</h5> : "" }
</div>
<Accordion/>
</div>
<div onClick={() => {
this.handleClick()
}} className={!this.props.visible ? 'open-side-menu-button' : 'hide' }></div>
</div>
);
}
}
MenuSide.propTypes = {};
const mapStateToProps = (state) => {
return {
visible: state.visible
}
};
export default connect(mapStateToProps)(MenuSide);
MenuSideActions.js
export default function toggleVisibility () {
return {type: "TOGGLE_VISIBILITY", visible: visible}
}
MenuSideReducer.js
const DEFAULT_STATE = {
visible: true
};
const toggleVisibility = (state, action) => {
return Object.assign({}, state, {visible: !action.visible});
};
export default (state = DEFAULT_STATE, action) => {
switch(action.type){
case "TOGGLE_VISIBILITY": {
return toggleVisibility(state, action);
}
}
return state;
};
我收到错误说&#34;可见&#34;没有定义,但我不知道我在哪里绊倒!
任何指导都会受到赞赏,如果我可以使用它,这个Redux看起来很有用:-P
答案 0 :(得分:2)
首先,你得到的错误可能来自这里:
visible
此范围内没有export default function toggleVisibility () {
return {type: "TOGGLE_VISIBILITY"}
}
变量 - 您是否打算将其作为参数?最好的解决方案是只在减速器内部设置切换逻辑(正如您已经拥有的那样)。因此,将操作重写为:
const toggleVisibility = (state, action) => {
return Object.assign({}, state, {visible: !state.visible});
};
还原剂:
dispatch
此外,您应该修改您的连接调用并传递第二个函数以将const mapStateToProps = (state) => {
return {
visible: state.visible
}
};
const mapDispatchToProps = (dispatch) => {
return {
toggle: () => {
dispatch(toggleVisibility());
}
}
}
export default connect(mapStateToProps)(MenuSide);
映射到props:
handleClick()
然后修改handleClick() {
this.props.toggle();
}
:
$('#mode_selector').bootstrapSwitch('state',true);