[英]Game of Life using React-Redux
目前,我正在FCC中構建“生活游戲” ,我認為這將是一個測試我對React-Redux的知識的好項目。
因為我是Redux的新手,所以我很難理解在這個項目中什么是愚蠢的組件還是智能組件。
在我看來,這是我的看法:
注意:當我說“智能組件”與“啞組件”時,我只是表示要成為“智能組件”,它是一個容器,或者與應用程序狀態相關聯的東西,而“啞組件”只是意味着它的工作就是簡單地渲染正在饋送的內容。
如果我的假設正確,那么我將很難在單元格上正確設置應用程序狀態。
到目前為止,這是我寫的內容:
組件/ board.js
import React, { Component } from 'react';
import Cell from '../containers/cell'
export default class Board extends Component {
constructor(props){
super(props);
this.state = {height: 18, width: 40}
this.test = this.test.bind(this)
}
test(){
console.log(this.state)
}
render(){
let rows = [];
for (var i = 0; i < this.state.height; i++){
let rowID = `row${i}`
let bin = []
for (var idx = 0; idx < this.state.width; idx++){
let cellID = `cell${i}-${idx}`
bin.push(<Cell key={cellID} id={cellID}/>)
}
rows.push(<tr key={i} id={rowID}>{bin}</tr>)
}
return(
<div className="container">
<div className="row">
<div className="col s12 board"></div>
<table id="simple-board">
<tbody>
{rows}
</tbody>
</table>
</div>
</div>
)
}
}
容器/ cell.js
import React, { Component } from 'react';
// import from '../actions/index';
// import { connect } from 'react-redux';
// import { bindActionCreators } from 'redux';
export default class Cell extends Component{
constructor(props){
super(props);
this.state = {
color: 'dead'
};
this.test = this.test.bind(this);
}
test(){
this.state.color === 'dead' ? this.setState({color:'alive'}) : this.setState({color:'dead'})
}
render(){
return (
<td
className={this.state.color}
key={this.props.cellID}
id={this.props.cellID}
onClick={this.test}>
</td>
)
}
}
// function mapDispatchToProps(dispatch){
// return bindActionCreators({}, dispatch)
// }
// export default connect(null,mapDispatchToProps)()
我不確定目前該如何處理。 起初,我考慮過將所有單元格包裝在一個數組中,這將是應用程序的狀態,但是我不確定該如何進行。
任何回應將不勝感激
我建議您使自己的層次結構像這樣。 我將使用類似於JSON的語法來表示組件層次結構,以便您可以理解:
App (smart) {
dispatchProps: {
...gameControlActions, // gets passed into GameControls
onCellClick, // gets passed down to Board, and then to each Cell
}
stateProps: {
cells: [{
id: #
status: 'dead', // or 'alive'
}], // gets passed down to Board, to render cells
...generationData, // gets passed down to Generation
}
}
// Children of App
GameControls (dumb) // start, clear, randomize
Board (dumb)
Cells (dumb)
Generation (dumb)
渲染單元格時,您將像這樣渲染它們:
<Cell key={cellID} id={cellID} status={status} onClick={this.props.onCellClick} />
在Cell
組件內部, render
函數將如下所示,您現在可以擺脫state
:
render(){
return (
<td
className={this.props.status}
id={this.props.id}
onClick={this.props.onClick.bind(null, this.props.id)}>
</td>
)
}
您的onCellClick
操作將如下所示:
function onCellClick(cellId) {
return {
type: 'CELL_CLICK',
payload: cellId,
};
}
然后,您可以通過切換單元格數組中該單元格的status
(記住返回一個新的cells
副本)在減速器中處理該動作。 另外,如有必要,您可能需要使Cell
組件擴展PureComponent
,以加快對帳過程或實現shouldComponentUpdate
。
讓我知道這是否沒有道理,或者您有疑問(我想您會)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.