I have a react component which has a list of selectable items. I want the list to be hidden until the user clicks a button to show the list.
There is no reason for the 'showList' to be a part of the global store, as it only matters to this component.
I am using redux connect, and am having difficulting understanding how to access the local components this.setState
as it is always 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;
In the example provided, You are using react state less Component. You cannot access state in such components. Use normal components to have the state in component.
class SpeedControls extends Component {
render() {
}
}
mapDispatchToProps
is just utility function provided by react-redux, It is not a component.There is no way you can access or update state there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.