[英]Proper way to use Action in Redux
我正在研究一款色彩猜謎游戲。 我有一個稱為generateColors()
,該操作生成9種顏色,並且將從這9種顏色中隨機選擇一個答案。 我的App.js
呈現Header.js
和BoxGrid.js
。
目前,我在BoxGrid.js
調用generateColors()
。 將答案傳遞給Header.js
的正確方法是什么? 我應該改為在App.js
調用generateColors()
嗎?
BoxGrid.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Box from '../components/box';
import { generateColors } from '../actions';
class BoxGrid extends Component{
componentDidMount(){
this.props.generateColors();
}
render(){
return(
<div>
<div className="grid">
{this.props.colors.map((color)=>{
return <Box key={color} color={color}/>
})}
</div>
</div>
)
}
}
function mapState({colors}){
return {colors};
}
export default connect(mapState,{generateColors})(BoxGrid);
提前致謝。
我不確定應用程序的外觀,所以我可能是錯的。
因為您使用的是Redux,所以只需將答案保存到Redux商店中,然后將Header
到商店(或僅連接App
並將道具傳遞給Header
,都可以)
就我個人而言,在這種情況下,我希望將該動作放入App.js中,因此BoxGrid
不需要關心任何應用程序邏輯,只需呈現UI。 但是我認為這只是個人喜好,沒有正確的答案。
您可以在此處查看Redux文檔的常見問題解答:
我應該只連接頂部組件,還是可以連接樹中的多個組件?
我以answer
假設您的意思是用戶正在選擇一種顏色,並且您希望將該用戶輸入從一個組件傳遞到另一組件。 有兩種方法可以做到這一點。 您可以將App
中的一個函數作為prop傳遞給下面的組件,並在調用該函數時在App
設置本地狀態,該狀態也傳遞給子組件:
class App extends Component {
constructor(props) {
super(props)
this.state = {
answer: null
}
}
updateAnswer(answer) {
this.setState({ answer: answer })
}
render () {
return <div>
<Header answer={this.state.answer} />
<BoxGrid answer={this.state.answer} updateAnswer={this.updateAnswer.bind(this)} />
</div>
}
}
然后,當BoxGrid
調用this.props.updateAnswer(answer)
,它將傳遞到標頭。 這不使用Redux存儲。
另一種方法是使用Redux存儲,並調用一個動作。 如果要在多個組件之間共享數據,則可能比使用上面的本地狀態更有意義。 與您已經發布的內容非常相似,您可以連接任何組件並獲取全局狀態。 除了在App
組件中設置本地狀態外,您還可以使用一個answer
減少器,它看起來像:
function answer (state = { answer: null }, action) {
if (action.type === 'saveAnswer') {
return { answer: action.answer }
}
}
還有一個saveAnswer動作創建者,例如:
function saveAnswer (answer) {
return {
type: 'saveAnswer',
answer: answer
}
}
然后,如果將App
組件與mapStateToProps
函數連接mapStateToProps
,則只需從商店中獲取答案並將其作為道具返回即可,它可以向下傳遞給任何子組件。 隨着層次結構變得越來越復雜,您可以選擇連接任何子組件,但是如果您只有3個組件,那么僅連接App
並從商店傳遞數據作為道具可能更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.