【发布时间】:2018-09-20 05:27:07
【问题描述】:
我发现了很多关于该主题的问题,但我找不到与我的完全一样的示例。单击按钮添加用户后,我尝试重置输入值。如何在带有受控组件的 redux 中做到这一点? 我的代码: 组件:
class Userlist extends Component {
constructor(props) {
super(props)
this.state = {
data: this.props.ui.users
}
}
render() {
console.log(this.props)
return (
<div>
<input type="text"
value={this.props.ui.inputName}
name="username"
onChange={(e) => this.props.uiActions.handleNameChange(e.target.value)}/>
<input type="text"
value={this.props.ui.inputEmail}
name="email"
onChange={(e) => this.props.uiActions.handleEmailChange(e.target.value)}/>
<table>
<thead>
<tr>
<th>LP</th>
<th>USER</th>
<th>E-MAIL</th>
</tr>
</thead>
<tbody>
{this.props.ui.users.map((item, index) => {
return (
<tr key={index}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.email}</td>
</tr>
)
})}
</tbody>
<tfoot>
</tfoot>
<button onClick={() => this.props.uiActions.addUser(this.state.username)}>add</button>
</table>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
return {
uiActions: bindActionCreators(UI_ACTIONS, dispatch)
};
}
function mapStateToProps(state) {
return {
ui: state.ui
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Userlist);
我处理输入/添加用户的操作: https://github.com/KamilStaszewski/crudapp/blob/develop/src/actions/ui_actions.js
const initialState = {
users: [],
name: '',
email: '',
inputName: undefined,
inputEmail: undefined
}
export default (state = initialState, action) => {
switch (action.type) {
case UI_ACTIONS.SET_REPOS:
return { ...state, users: action.users };
case UI_ACTIONS.ADD_USER:
return {...state, users: action.users, inputName: '', inputEmail: '' };
case UI_ACTIONS.UPDATE_NAME:
return {...state, name: action.val };
case UI_ACTIONS.UPDATE_EMAIL:
return {...state, email: action.val};
default:
return state;
}
};
我知道受控/不受控输入存在问题。我也想在 redux 中重置输入,因为即使单击按钮后输入值消失,但如果您第二次使用相同的值单击它,这些值仍然存在。如何正确重置?我想以正确的方式去做。谢谢。
【问题讨论】:
-
您是否尝试过使用 key 作为输入字段,因为使用 key 会按照 react docs 中的建议重新初始化表单组件,请在阅读此博客 reactjs.org/blog/2018/06/07/… 后尝试
-
下班后试试,谢谢!
标签: reactjs ecmascript-6 react-redux