[英]Set local state of component with Redux props given from mapStateToProps()
[英]mapStateToProps initial value from props, then only state
我有一些組件的React組件。 道具被賦予一個mapStateToProps。
const mapStateToProps = (state, {props}) => {
return {
feeds: props.feeds,
feedEntries: props.feedEntries,
....
一旦用戶開始與UI交互,他們就可以更改狀態。 此時,組件需要使用state
而非props
更新自身。
const mapStateToProps = (state, {props}) => {
return {
feeds: state.feeds,
feedEntries: state.feedEntries,
....
如何自舉一個mapStateToProps
函數,以便在首次加載時直接使用賦予組件的props。 接下來,僅聲明其為數據狀態?
使用三元檢查state屬性是否為undefined
,並相應地獲取props
值:
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds === undefined ? props.feeds : state.feeds,
feedEntries: state.feedEntries === undefined ? props.feedEntries : state.feedEntries,
....
如果您知道屬性不會將偽造的值(false,null,0等)作為合法值,則可以將三元數替換為短路評估 :
const mapStateToProps = (state = {}, props) => {
return {
feeds: state.feeds || props.feeds,
feedEntries: state.feedEntries || props.feedEntries,
....
我建議您采取另一種方法,而不是中斷mapStateToProps
函數流,而最好從props獲取內部值,然后由用戶更改的值保存在狀態上,您的render函數應支持該狀態並檢查是否是否收到任何用戶數據
結束了以下操作。
export default (initProps) => {
const combinedState = {
...defaultState,
...initProps,
};
return createStore(
reducer,
combinedState,
applyMiddleware(logger, thunk),
)
};
創建了一個包裝createStore函數..的函數,該函數接受由1)組成的對象。 提供給主要組件的道具(initProps)和2)。 defaultProps
—以商店的默認形狀導入到此文件中的JS對象,init道具覆蓋defaultProps中的任何值。
export default (props) => {
const store = configStore(props);
return (
<Provider store={store}>
<Editor props={{ ...props }} />
</Provider>
)
}
主要組件是獲取道具,將這些道具傳遞給config store功能。 使用上面的組合對象構建商店。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.