0
我有一個具有可選項目列表的反應組件。我想讓列表隱藏,直到用戶單擊按鈕顯示列表。更新反應組件狀態與REDEX存儲區分開
'showList'沒有理由成爲全球商店的一部分,因爲它只對這個組件有影響。
我使用的是redux連接,並且我很難理解如何訪問本地組件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;
您正在使用無狀態組件。創建一個正常的控制器,並在像componentWillMount這樣的現場循環事件中使用'this.setState'。 – Hosar
我不知道這是否有效。 'toggleList:()=> {showList =!showList;調度();}'。但這是一個簡單的方法。 –