我有一个react组件,其中包含可选项列表。我希望隐藏列表,直到用户单击按钮以显示列表。
没有理由显示' showList'成为全球商店的一部分,因为它只对这个组件有用。
我正在使用redux connect,并且难以理解如何访问本地组件this.setState
,因为它总是undefined
。
// Redux connect
import { connect } from 'react-redux'
import { setClockSpeed } from '../actions'
import SpeedControls from '../components/speedControl/SpeedControl'
let showList = false;
const mapStateToProps = (state) => {
return {
speed: state.clock.speed,
speeds: [ 1, 5, 10, 25, 50, 100, 150, 200 ],
showList
}
}
const mapDispatchToProps = (dispatch) => {
return {
setClockSpeed: newSpeed => displatch(setClockSpeed(newSpeed)),
toggleList: this.setState({showList: !showList}) //undefined here
}
}
const PlayerSpeedControls = connect(
mapStateToProps,
mapDispatchToProps
)(SpeedControls)
export default PlayerSpeedControls
// Component
import React, { PropTypes } from 'react';
import style from './SpeedControl.css';
const getSpeedItemClass = (s, idx, speed, speeds) => {
let speedClass = style.speedItem;
if (idx === 0) speedClass += ' ' + style.lastSpeedItem;
if (idx === speeds.length - 1 ) speedClass += ' ' + style.firstSpeedItem;
if (s === speed) speedClass += ' ' + style.currentActiveSpeed;
return speedClass
}
const SpeedControls = ({ setClockSpeed, toggleList, speed, speeds, showList }) => (
<div className={style.speedControl}>
<div className={style.speedList}>
<ul className={showList ? style.speedOptions : style.hideSpeedOptions}>
{ speeds.map((s, idx) => {
return <li key={idx} className={getSpeedItemClass(s, idx, speed, speeds)} onClick={(s) => {
}}>{s}x</li>
})
}
</ul>
<span className={style.currentSpeed} onClick={ toggleList || this.setState //undefined here too }>{speed}x</span>
</div>
</div>
);
SpeedControls.propTypes = {
setClockSpeed: PropTypes.func.isRequired,
speed: PropTypes.number.isRequired,
speeds: PropTypes.array.isRequired
};
export default SpeedControls;
答案 0 :(得分:1)
在提供的示例中,您正在使用react state less Component。您无法访问此类组件中的状态。使用normal components将状态置于组件中。
class SpeedControls extends Component {
render() {
}
}
mapDispatchToProps
只是react-redux提供的实用功能,它不是一个组件。你无法在那里访问或更新状态。