我是新手做出反应,试图制作侧边栏。
到目前为止,我已成功达到减速机。
// sidebarReducer.js
const sidebar = (state = { visible: false }, action) => {
switch (action.type) {
case "SHOW":
console.log("show");
return { ...state, visible: true };
case "HIDE":
console.log("hide");
return { ...state, visible: false };
default:
return state;
}
};
export default sidebar;
.
class SidebarContainer extends Component {
handleOpen = () => {
this.props.dispatch({ type: 'SHOW'});
}
handleClose = () => {
this.props.dispatch({ type: 'HIDE'});
}
handleToggle = () => {
const { visible } = this.props;
const { handleClose, handleOpen } = this;
if(visible) return handleClose();
handleOpen();
console.log(visible); // ouput : undefined.
}
render(){
const { visible } = this.props;
const { handleToggle, handleClose } = this;
return[
visible && <Dimmer onClick={handleClose} key="dimmer"/>,
<Sidebar visible={visible} onClose={handleClose} key={0}/>,
<Hamburger active={visible} onToggle={handleToggle} key={1}/>
]
}
}
export default connect()(SidebarContainer);
当调用handleToggle事件时,我得到两个日志,它们来自sidebarReducer.js的console.log(“show”)的“show”和来自SidebarContainer.js的console.log(可见)的“undefined”。
当可见光为真时,将显示调光器,侧边栏,汉堡包组件。但由于我不知道为什么可见不明确的原因,它没有显示。你能告诉我原因吗?
在render
内你从visible
进口this.props
:
const { visible } = this.props;
但他们如何传递给组件道具?
visible
值存储在Redux中并且应该连接到React组件,因此您可以使用它。
如你所见,没有任何关联:
export default connect()(SidebarContainer);
所以你需要像这样连接它:
const mapStateToProps = state => {
return {
visible: state.REDUCER_NAME.visible // propably sidebar
}
}
export default connect(mapStateToProps, null)(SidebarContainer);
请查看Redux Doc中的Implementing Components部分。为了更深入的了解
注意:关于动作的相同的事情(你从道具调用的函数:this.prop.actionName
- 它们也应该连接到组件,通过mapDispatchToProps
)
您必须将组件连接到状态/操作。
export default connect(state => ({
visible: state.sidebar.visible
}),
{
show: sidebarActions.show
}
)(SidebarContainer);
类似的东西。
检查:redux文档中的mapStateToProps和mapDispatchToProps方法