【发布时间】:2017-11-12 20:04:18
【问题描述】:
我有一个简单的 redux/react 应用程序。它工作正常,只是它不显示初始状态(用户得分)。感谢您的帮助! 减速机如下:
const initialState = [{userScore: 0, computerScore :0}];
const dataReducer = (state = initialState, action) => {
switch (action.type) {
case 'USER_WINS':
return [
{
userScore: state.userScore + 1,
computerScore: state.computerScore
}
]
case 'COMPUTER_WINS':
return [
{
userScore: state.userScore,
computerScore: state.computerScore +1
}
]
default:
return state
}
}
主类如下:
class Interface extends Component{
constructor(props) {
super(props);
this.computerChoice = this.computerChoice.bind(this);
this.userChoice = this.userChoice.bind(this);
}
computerChoice () {
var choicesArray = ['Paper','Rock','Scissors'];
var computerResponse = choicesArray[Math.floor(Math.random() * 3)];
return computerResponse;
}
userChoice (userInput){
var computerInput = this.computerChoice();
if (
(userInput === 'Rock' && computerInput === 'Scissors')||
(userInput === 'Paper' && computerInput === 'Rock') ||
(userInput === 'Scissors' && computerInput === 'Paper')
) {
this.props.userWinsGame();
} else {
}
}
render() {
const value = this.props;
return (
<div>
这是我要显示分数的地方:
Human: {value.userScore}
Computer: {value.computerScore}
<br/>
<button value='Rock' onClick={(e) => this.userChoice(e.target.value)} >Rock</button>
<button value='Paper' onClick={(e) =>this.userChoice(e.target.value)} >Paper</button>
<button value='Scissors' onClick={(e) =>this.userChoice(e.target.value)} >Scissors</button>
</div>
)
}
}
一切都在这里派发:
const render = () => ReactDOM.render(
<Interface
value={store.getState()}
userWinsGame = {() => store.dispatch({ type: 'USER_WINS' })}
computerWinsGame = { () => store.dispatch({ type: 'COMPUTER_WINS'
})}
/>,
root
)
感谢您的帮助 - 一切正常,但显示初始状态!
【问题讨论】:
标签: javascript reactjs redux