我已经创建了一个Create- react -App react应用程序& Redux。
我使用connect (通过mapStateToPrope)将我的userReducer映射到state,即:
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 }
}这是从props获取初始值的推荐方法吗?
发布于 2018-02-21 22:40:09
您正在尝试使用受控输入,但没有提供有关更新状态的信息。
如果只想提供初始状态,可以使用输入字段的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);发布于 2018-02-21 22:44:29
为了在本地状态或redux中管理发生的更改,您需要按如下方式调用函数onChange
onChange={(e) => this.updateField('fieldName',e.target.value,e)}当属性(或状态)更新时,value字段将会并将始终更新
value={this.props.fieldName}或
value={this.state.fieldName}你的onChange函数要么调用setState({fieldName: value})来设置本地状态,要么调度到redux来更新存储,后者将通过mapStateToProps函数更新本地状态。
发布于 2018-02-21 22:53:59
对受控组件执行此操作没有任何错误。但是您犯的一个错误是构造函数中没有this.props。使用props变量将道具直接传递给构造函数。因此代码将是
this.state = {
FirstName: props.userProfile.firstName
};但是,如果您希望稍后在组件上更新存储中的值,请声明componentWillReceiveProps()并在其中设置状态值,以便在此处捕获存储中的更改。
https://stackoverflow.com/questions/48908527
复制相似问题