Javascript 通过复选框项的本地状态更新redux状态
stackoverflow中也有类似的问题,但我没有找到我想要的。 我有一个donorDonationForm,它是一个连接到redux状态的类componenet。该组件的作用是收集有关一个人想要捐赠电子产品的信息。此时,我想将这些项保存在一个数组中(将来可能使用对象)。 我的redux状态保存捐赠者信息,还原程序如下所示:Javascript 通过复选框项的本地状态更新redux状态,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,stackoverflow中也有类似的问题,但我没有找到我想要的。 我有一个donorDonationForm,它是一个连接到redux状态的类componenet。该组件的作用是收集有关一个人想要捐赠电子产品的信息。此时,我想将这些项保存在一个数组中(将来可能使用对象)。 我的redux状态保存捐赠者信息,还原程序如下所示: import {CHANGE_INPUT_FIELD} from '../utils/constants'; const initialStateInputs = {
import {CHANGE_INPUT_FIELD} from '../utils/constants';
const initialStateInputs = {
// update the state
donorFields: {
name: '',
phone: '',
area: '',
yeshuv: '',
address: ''
// dateOfOffer: ''
},
donationFields: {
// donorID: '',
// vulonteerID: '',
type: [],
quantity: 1,
status: 'NOT_HANDLED',
comments: ''
// lastDateHandled: ''
}
// }, items: [ //need to add quantity
// {id: 1, name: "LAPTOP", isChecked: false, label: 'מחשב'},
// {id: 2, name: "HEADPHONES", isChecked: false, label: 'אוזניות'},
// {id: 3, name: "OTHER", isChecked: false, label: 'אחר'},
// ]
}
export const donorDonationInputsReducer = ( state = initialStateInputs, action={} ) => {
switch(action.type) {
case CHANGE_INPUT_FIELD:
return Object.assign( {}, state,
{
donorFields : {...state.donorFields,...action.payload},
donationFields: {...state.donationFields,...action.payload},
// items : {...state.items,...action.payload},
// isChecked: action.payload
})
default:
return state;
}
}
正如您所看到的,项目现在已被注释,我正在管理项目在本地状态下的状态,以及comp的外观:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { setInputField } from '../actions/formAction';
import CheckBox from '../components/CheckBox/CheckBox';
import FormInput from '../components/FormInput/FormInput';
import {selectAreasOptions_2} from '../utils/constants';
import "./form.css";
const mapStateToProps = (state) => {
return {
donorFields: state.donorDonationInputsReducer.donorFields,
donationFields: state.donorDonationInputsReducer.donationFields
}
}
const mapDispatchToProps = dispatch => {
return {
onInputChange: event => {
const {name, value} = event.target;
dispatch(setInputField( { [name]:value} ) )
}
}
}
class donorDonationForm extends Component {
constructor() {
super();
this.state = {
items: [
{id: 1, name: "LAPTOP", isChecked: false, label: 'מחשב'},
{id: 2, name: "HEADPHONES", isChecked: false, label: 'אוזניות'},
{id: 3, name: "OTHER", isChecked: false, label: 'אחר'},
]
,
type: []
}
}
handleCheckChieldElement = (event) => {
let {items, type} = this.state;
let arr = [];
items.forEach(item => {
if (item.name === event.target.value) {
item.isChecked = event.target.checked;
// console.log(`item.name :${item.name }`);
// console.log(`event.target.value :${event.target.value}`);
// console.log(`event.target.checked :${event.target.checked}`);
}
})
items.map(item => item.isChecked ? arr.push(item.name) : null)
this.setState({items: [...items], type: [...arr]});
}
onButtonSubmit = (event) => {
console.log(this.props.donorFields);
event.preventDefault();
fetch('http://localhost:8000/api/donor', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
...this.props.donorFields
})
})
.then(response => response.json())
.then(resp => console.log(resp))
.catch( err => console.log(err) )
}
// componentDidUpdate(prevProps, prevState) {
// const {items, type} = this.state;
// // const type = [];
// if (prevState.items !== items) {
// console.log('items state has changed');
// items.map (item => item.isChecked ?
// this.setState({type: [...type,item.name]}) : null)
// // if (item.isChecked) { type.push(item.name) } ;
// console.log(type);
// }
// }
render() {
console.log(this.state.items);
console.log(this.state.type);
const { onInputChange } = this.props;
return (
<div>
<h1 className="pt4"> פרטי תורם</h1>
<form className=" black-80 pt2" >
<section className=" grid-container">
<FormInput
id="name"
name="name"
type="text"
onInputChange={onInputChange}
label="שם "
required
/>
<FormInput
id="phone"
name="phone"
type="tel"
onInputChange={onInputChange}
label="מספר טלפון "
required
/>
<FormInput
id="address"
name="address"
type="text"
onInputChange={onInputChange}
label="כתובת "
required
/>
<FormInput
id="yeshuv"
name="yeshuv"
type="text"
onInputChange={onInputChange}
label="עיר "
required
/>
<FormInput
id="comments"
name="comments"
onInputChange={onInputChange}
label="הערות "
required
/>
<FormInput
id="area"
name="area"
onInputChange={onInputChange}
label="איזור "
select={selectAreasOptions_2}
/>
{/* type */}
<div className="measure-narrow">
<label htmlFor="type" className="f5 b db mb2">מעוניין לתרום
<span className="normal black-60"> *</span>
</label>
{
this.state.items.map( (item, i) => {
return (
<CheckBox
key={i}
onChange={this.handleCheckChieldElement}
checked={ item.isChecked }
value= {item.name}
label = {item.label}
/>
);
})
}
</div>
</section>
<input type="submit" value="שלח"
className="b bg-light-blue pa2 hover pointer"
onClick={this.onButtonSubmit}
/>
</form>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(donorDonationForm);
import React,{Component}来自'React';
从'react redux'导入{connect};
从“../actions/formAction”导入{setInputField};
从“../components/CheckBox/CheckBox”导入复选框;
从“../components/FormInput/FormInput”导入FormInput;
从“../utils/constants”导入{selectAreasOptions_2};
导入“/form.css”;
常量mapStateToProps=(状态)=>{
返回{
donorFields:state.DonorOnationInputsReducer.donorFields,
捐赠字段:state.donorOnationInputsReducer.donationFields
}
}
const mapDispatchToProps=调度=>{
返回{
onInputChange:event=>{
常量{name,value}=event.target;
分派(setInputField({[name]:value}))
}
}
}
类donorDonationForm扩展了组件{
构造函数(){
超级();
此.state={
项目:[
{id:1,名称:“笔记本电脑”,被检查为:假,标签为:',
{id:2,名称:“耳机”,被检查为:假,标签为:',
{id:3,名称:“其他”,被选中:false,标签:'אחר'},
]
,
类型:[]
}
}
HandleCheckChielElement=(事件)=>{
设{items,type}=this.state;
设arr=[];
items.forEach(item=>{
if(item.name==event.target.value){
item.isChecked=event.target.checked;
//log(`item.name:${item.name}`);
//log(`event.target.value:${event.target.value}`);
//log(`event.target.checked:${event.target.checked}`);
}
})
items.map(item=>item.isChecked?arr.push(item.name):null)
this.setState({items:[…items],type:[…arr]});
}
OnButtonsSubmit=(事件)=>{
console.log(this.props.donorFields);
event.preventDefault();
取('http://localhost:8000/api/donor', {
方法:“post”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
…这是道具,多诺菲尔德
})
})
.then(response=>response.json())
.然后(resp=>console.log(resp))
.catch(err=>console.log(err))
}
//componentDidUpdate(prevProps、prevState){
//const{items,type}=this.state;
////常量类型=[];
//if(prevState.items!==项){
//log('items state has change');
//items.map(item=>item.isChecked?
//this.setState({type:[…type,item.name]}):null)
////如果(item.isChecked){type.push(item.name)};
//console.log(类型);
// }
// }
render(){
console.log(this.state.items);
console.log(this.state.type);
const{onInputChange}=this.props;
返回(
פרטי תורם
{/*类型*/}
מעוניין לתרום
*
{
this.state.items.map((item,i)=>{
返回(
);
})
}
);
}
}
导出默认连接(MapStateTrops、mapDispatchToProps)(donorDonationForm);
我的主要目标是,类型数组(最终捐赠)将在提交此表单之前更新redux状态。我尝试了componentDidUpdate,但没有成功。跟踪选中项目、更新数组然后更新类型数组(redux状态下的最终捐赠)的最佳方式是什么?我是否应该在onButtonSubmit方法中执行此操作-在将数据发送到服务器之前(这是保存项数组上的循环以搜索选中的元素的方法)?更好的方法是在
onButtonSubmit中执行
让我简单地解释一下任务:
inputChangeHandler
更新此.state.items
使用最后一个this.state.items
valueitems数组
insideon按钮提交
获得API响应后,使用项数组更新应用程序级别的Redux状态
注意:发送操作。Reducer将更新Redux状态。以下代码将执行此操作:
// Action
export const setItems = (data) => (dispatch) => {
dispatch({type: 'SET_ITEMS', payload: data})
}
// mapDispatchToProps
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
setItems,
...others
},
dispatch
)
// onSubmitButton
onButtonSubmit = (event) => {
console.log(this.props.donorFields);
event.preventDefault();
fetch('http://localhost:8000/api/donor', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
...this.props.donorFields
})
})
.then(response => this.props.setItems(response.json())) // will update the state.
.then(resp => console.log(resp))
.catch( err => console.log(err) )
}
// Reducer
export const donorDonationInputsReducer = ( state = initialStateInputs, action={} ) => {
switch(action.type) {
case CHANGE_INPUT_FIELD:
return Object.assign( {}, state,
{
donorFields : {...state.donorFields,...action.payload},
donationFields: {...state.donationFields,...action.payload},
// items : {...state.items,...action.payload},
// isChecked: action.payload
})
case SET_ITEMS:
return {
...state,
items: action.payload
}
default:
return state;
}
}
就这样
快乐编码:)感谢您的快速响应!因此,您的建议是等待来自捐赠路由的api响应,然后在发送第二个api req(捐赠数组)之前更新rhe redux状态,但是如何从本地状态更新redux状态?这是什么命令?我已经在我的答案中添加了解决方案。请看一看