[英]Need help to call an action using redux as well as update Component State on a single event of Click?
I am trying to learn Redux by simply add/delete users.我试图通过简单地添加/删除用户来学习 Redux。 I have an action 'ADD_PROFILE', with payload : name,account-number.
我有一个操作“ADD_PROFILE”,有效载荷为:名称,帐号。 On clicking add button, I wanted to update the store, hide the 'add user' form and show a message 'User added successfully'.
单击添加按钮时,我想更新商店,隐藏“添加用户”表单并显示消息“用户添加成功”。 If it is in React, I can have a boolean state variable, update/reset variable and switch the views.
如果它在 React 中,我可以有一个布尔状态变量,更新/重置变量并切换视图。 If I wanted to do the same using Redux bit not sure how.
如果我想使用 Redux 做同样的事情,我不确定如何。
This is what I tried :这是我试过的:
Action行动
export const addProfile = (name, account_number) => {
console.log(name, account_number)
return{
type :'ADD_PROFILE',
payload : {
name : name,
account_number : account_number
}
};
}
Reducer:减速器:
export default (profilesList=[],action) => {
switch(action.type){
case 'ADD_PROFILE':
return [...profilesList, action.payload]
case 'DELETE_PROFILE':
return profilesList.filter(name => name!== action.payload.name)
default:
return profilesList;
}
}
AddView.js添加视图.js
import React from 'react';
import { connect } from 'react-redux';
import { addProfile } from '../actions';
class AddView extends React.Component{
constructor(props) {
super(props);
this.state={
isProfileAdded: false
};
}
addValuesView(){
return(
<div>
Name : <input type="text" value={this.props.profiles.name} ref={el => (this.nameInputRef = el)}/>
Account Number : <input type="text" value={this.props.profiles.account_number} ref={el => (this.accountInputRef = el)}/>
<button onClick={() => {
this.setState(isProfileAdded=true),
this.props.addProfile(this.nameInputRef.value,this.accountInputRef.value)
}
}>Add</button>
</div>
);
}
profileAddedView(){
return(
<div>Profile added succesfully</div>
)
}
view(){
return !this.props.profiles.isProfileAdded ? this.addValuesView() : this.profileAddedView()
}
render(){
console.log(this.state)
return this.view()
}
}
const mapStateToProps = (state) => {
return { profiles : state.profiles }
}
const mapDispatchToProps = dispatch => ({
onAddProfile: dispatch(addProfile())
});
export default connect(mapStateToProps, {addProfile}) (AddView);
App.js应用程序.js
import React from 'react';
import AddView from './AddView';
const App = () =>{
return (
<div className="ui container">
<AddView />
</div>
);
}
export default App;
Method this.setState
should receive an object:方法
this.setState
应该接收一个对象:
() => {
this.setState({ isProfileAdded: true});
this.props.addProfile(this.nameInputRef.value, this.accountInputRef.value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.