这只是一个示例代码,我试图使用Redux控制我的受控输入,我将Redux添加到我的React项目中,并添加我的reducer和action,但是一切正常,除了在我的一个action中更新了我的组件。 以下代码是我的Reducer:
import actionTypes from "./actions";
const uniqid = require("uniqid");
const firstID = uniqid();
const initialState = {
cons: [
{
value: "",id: firstID,added: false
}
],pros: [
{
value: "",num: 0
};
const reducer = (state = initialState,action) => {
const newState = { ...state };
switch (action.type) {
case actionTypes.HANDLEINPUTCHANGE:
// const newState = state;
const changingItem = newState[action.case].find(item => {
return item.id === action.id;
});
const changingItemIndex = newState[action.case].findIndex(item => {
return item.id === action.id;
});
changingItem.value = action.event;
if (
changingItemIndex === newState[action.case].length - 1 &&
!changingItem.added
) {
alert(123);
const newItem = {
id: uniqid(),value: "",added: false
};
newState[action.case].push(newItem);
changingItem.added = true;
console.log(newState);
}
newState[action.case][changingItemIndex] = changingItem;
return newState;
case actionTypes.CLICK:
newState.num += 1;
return {
...newState
};
default:
return state;
}
};
export default reducer;
并且以下代码是我的组件,很遗憾,HANDLEINPUTCHANGE操作类型未更新我的组件:
import React,{ Component } from "react";
import FormElement from "../../base/components/formElement/FormElement";
import actionTypes from "../../base/store/actions";
import { connect } from "react-redux";
import "./style.scss";
class FormGenerator extends Component {
render() {
console.log(this.props);
return (
<ul classname="row formGeneratorContainer fdiColumn">
<li onClick={this.props.click}>{this.props.num}</li>
{this.props[this.props.case].map((item,index) => {
return (
<li classname="row formGeneratorItem" key={index}>
<div classname="bullet d_flex jcCenter aiCenter">1</div>
{/* <FormElement onChange={(e,index,type,)}/> */}
<input
name={item.id}
type="text"
onChange={event =>
this.props.onFieldValueChange(
event.target.value,this.props.case,item.id
)
}
/>
</li>
);
})}
</ul>
);
}
}
const mapstatetoProps = state => {
return {
cons: state.cons,pros: state.pros,num: state.num
};
};
const mapDispachToProps = dispatch => {
return {
onFieldValueChange: (event,c,id) =>
dispatch({
event: event,index: index,case: c,id: id,type: actionTypes.HANDLEINPUTCHANGE
}),click: () => dispatch({ type: actionTypes.CLICK })
};
};
export default connect(
mapstatetoProps,mapDispachToProps
)(FormGenerator);