簡體   English   中英

使用重組,如何用常規屬性從狀態覆蓋映射的屬性?

[英]using recompose, how overwrite mapped prop from state, with regular prop?

構建簡單的電話輸入表單組件:

class PhoneSettingsScreen extends React.Component {
    render() {
        const {changePhoneInput, submitPhone, errorText, loading} = this.props
            return (
                <View>
                    <TextInput onChangeText={changePhoneInput}/>
                        <Text style={{color: 'red'}}>{errorText}</Text>
                        <Button
                            onPress={submitPhone}
                        />
                        {loading && <Spinner/>}
                    </View>
                </View>
            )
        }
    }

當用戶在字段中鍵入電話時,此功能會更新errorText

const changePhoneInput = props => phone => {
    const {setPhone, setErrorText} = props
    setPhone(phone)
    let error = /[0-9]{6,9}/g.test(phone) ? '' : "Please enter valid number";
    setErrorText(error)
};

此代碼增強了組件,您可以看到errorText也來自redux狀態:

const enhance = compose(
    withState('errorText', 'setErrorText', ''),
    connect((state, nextOwnProps) => {
        state = state.get('settings')
        return {
            loading: state.get('loading'),
            errorText: state.get('error')
        }
    }, {
        submitPhoneAction
    }),
    withState('phone', 'setPhone', ''),
    withHandlers({
        changePhoneInput,
        submitPhone
    }),
)

當用戶單擊按鈕,並且網絡請求失敗時,我從reducer收到錯誤,然后將其映射為errorText映射到組件。 但是,當用戶再次編輯電話時,應顯示“請輸入有效號碼”錯誤,但是來自redux的道具仍然存在,而我的changePhoneInput不會更新道具。 如何避免這種情況?

我試圖更改撰寫功能的位置,但沒有幫助。 我基本上需要的是覆蓋errorText道具在我和組件changePhoneInput功能。 當然,我可以使用另一個變量名,但我認為應該有另一種方法來解決此問題。

您可以在connect覆蓋存儲狀態

const enhance = compose(
    withState('errorText', 'setErrorText', ''),
    connect((state, nextOwnProps) => {
        state = state.get('settings')
        return {
            loading: state.get('loading'),

            // You can override the store state here, ex:
            errorText: nextOwnProps.errorText || state.get('error')

        }
    }, {
        submitPhoneAction
    }),
    withState('phone', 'setPhone', ''),
    withHandlers({
        changePhoneInput,
        submitPhone
    }),
)

但是,我建議您看一下withStateHandlers ,它可以將withStatewithHandlers合並到一個HOC中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM