簡體   English   中英

將道具轉移到狀態的正確方法(如果需要)React&Redux

[英]Correct Way to Transfer Props to State (if needed) React & Redux

我創建了一個Create-React-App react app和Redux。

我正在使用連接將我的userReducer映射到狀態(通過mapStateToPrope),即:

function mapStateToProps({ userProfile }) {
return { userProfile: userProfile ? userProfile : null };
}

export default connect(mapStateToProps, fetchUserProfile)(Profile);

並且我有一個將UserProfile Firstname綁定到的輸入:

render(){
   return (
    <div>
       <input type="text" value={this.props.userProfile.firstName} />
   </div>
 ) 
}

現在的問題是我將其綁定到道具,無法更改它,如果我輸入輸入內容,則不會更改輸入內容。

如果我添加了onChange = {updateValue}方法,並嘗試更新道具,那么它將無法正常工作,因為組件無法更新自己的道具。

這樣就可以將道具轉移到狀態。

constructor(props){
    super(props);
    this.state = { FirstName : this.props.userProfile.firstName }
}

這是從道具獲得初始值的推薦方法嗎?

您正在嘗試使用受控輸入,而沒有提供有關更新狀態的信息。

如果只想提供初始狀態,則可以使用輸入字段的defaultValue屬性。

<input defaultValue={this.props.value} />

這樣,您可以輕松更改輸入值,而無需寫開銷。

但是,如果要更新組件,則應使用組件狀態(就像在onChange示例中所做的那樣),或者如果要向更多組件提供輸入值而不是輸入組件,則應使用redux狀態。

const Component = ({ firstname, updateFirstname }) => (
  <input
    onChange={updateFirstname}
    value={firstname}
  />
);

const mapStateToProps = state => ({
  firstname: state.profile.firstname,
});

const mapDispatchToProps = dispatch => ({
  updateFirstname: e => dispatch({ type: 'UPDATE_FIRSTNAME', firstname: e.target.value }),
});

connect(mapStateToProps, mapDispatchToProps)(Component);

為了使更改可以在本地狀態或redux中進行管理,您需要按以下方式調用onChange函數

onChange={(e) => this.updateField('fieldName',e.target.value,e)}

當道具(或狀態被更新)時,值字段將且將始終被更新。

value={this.props.fieldName}

要么

value={this.state.fieldName}

您的onChange函數可以調用setState({fieldName:value})來設置本地狀態,也可以分派到redux來更新Store,這將通過mapStateToProps函數來更新本地狀態。

對受控組件執行此操作沒有錯。 但是您犯的一個錯誤是,構造函數中沒有this.props 您正在使用props變量將props直接傳遞給構造函數。 所以代碼將是

this.state = {
  FirstName: props.userProfile.firstName
};

但是,如果您希望以后在組件上更新存儲中的值,則請聲明componentWillReceiveProps()並在那里設置狀態值,以便在此處捕獲存儲中的更改。

暫無
暫無

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

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