Reactjs 将道具转移到状态(如果需要)的正确方法;重演
我已经创建了一个Create-React-App-React-App&Redux 我正在使用connect将我的userReducer映射到状态(通过MapStateTrope),即: 我有一个输入,我将UserProfile Firstname绑定到:Reactjs 将道具转移到状态(如果需要)的正确方法;重演,reactjs,react-redux,Reactjs,React Redux,我已经创建了一个Create-React-App-React-App&Redux 我正在使用connect将我的userReducer映射到状态(通过MapStateTrope),即: 我有一个输入,我将UserProfile Firstname绑定到: render(){ return ( <div> <input type="text" value={this.props.userProfile.firstName} /> </
render(){
return (
<div>
<input type="text" value={this.props.userProfile.firstName} />
</div>
)
}
这是从道具获取初始值的推荐方法吗?您试图使用受控输入,而不提供有关更新状态的信息 如果只想提供初始状态,可以使用输入字段的
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);
const组件=({firstname,updateFirstname})=>(
);
常量mapStateToProps=状态=>({
名字:state.profile.firstname,
});
const mapDispatchToProps=调度=>({
updateFirstname:e=>dispatch({type:'UPDATE_FIRSTNAME',FIRSTNAME:e.target.value}),
});
连接(MapStateTrops、mapDispatchToProps)(组件);
为了在本地状态或redux中管理更改,您需要调用函数onChange,如下所示
onChange={(e) => this.updateField('fieldName',e.target.value,e)}
当道具(或状态)更新时,值字段将会并且将始终更新
或
onChange函数可以调用setState({fieldName:value})来设置本地状态,也可以分派到redux来更新存储,而redux将通过mapstatetrops函数更新本地状态。对于受控组件,这样做没有错。但是您犯的一个错误是构造函数中没有
this.props
。使用props
变量将props直接传递给构造函数。因此,代码将是
this.state = {
FirstName: props.userProfile.firstName
};
但是,如果您希望以后在组件上更新存储区中的值,请声明
componentWillReceiveProps()
,并在其中设置状态值,以便在此处捕获存储区中的更改。这将起作用。。我只需要设置初始值,允许用户更改该值,然后如果他们单击SAVE,则需要将整个userprofile拍摄到要通过AJAX更新的操作。。。因此,如果此方法未绑定,我需要在保存单击时以某种方式获取新值……好的,如果您只想在表单提交时发布状态,可以在表单中编写onSubmit处理程序,发布FormData对象。但也许我会选择组件状态路径,因为您不必处理FormData,您可以直接使用状态作为AJAX请求的JSON。:)如果您已经在使用redux,为什么不使用store(redux)?
onChange={(e) => this.updateField('fieldName',e.target.value,e)}
value={this.props.fieldName}
value={this.state.fieldName}
this.state = {
FirstName: props.userProfile.firstName
};