gpt4 book ai didi

reactjs - 将 Props 传输到状态的正确方法(如果需要)React 和 Redux

转载 作者:行者123 更新时间:2023-12-04 01:58:38 24 4
gpt4 key购买 nike

我已经创建了一个 Create-React-App react 应用程序和 Redux。

我正在使用连接将我的 userReducer 映射到状态(通过 mapStateToPrope)即:

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

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

我有一个输入,我已将 UserProfile 名字绑定(bind)到:

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

这个问题是现在我已经将它绑定(bind)到 props,我无法更改它,如果我输入输入,它不会更改输入中的文本..

如果我添加一个 onChange={updateValue} 方法,并尝试更新 prop,它将无法工作,因为组件无法更新它自己的 props。

这样就剩下将 props 转移到状态。

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

这是从 props 获取初始值的推荐方法吗?

最佳答案

您正试图在不提供有关更新状态的信息的情况下使用受控输入。

如果您只想提供一个初始状态,您可以使用输入字段的 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);

关于reactjs - 将 Props 传输到状态的正确方法(如果需要)React 和 Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48908527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com