.NET-starting-with-js-and-react guy again:)
我总是在不改变状态的情况下如何修改状态。有了新的ES6传播操作员,我想我不会再受苦了,但好像我做错了。
我尝试了各种方法如何将项添加到数组中(代码示例来自此link)
减速机:
const patientsInitialState = {
patients : [],
selectedPatient: {}
}
const PatientsReducer = (state = patientsInitialState, action) => {
switch(action.type) {
// other not related cases
case 'ADD_PATIENT':
return {
...state,
patients: [...state.patients, action.payload]
}
// also tried this:
//return {
// patients: [ ...state.patients, action.payload]
//}
default:
return state;
}
}
export default PatientsReducer;
组件:
handleAddPatientClick(patient) {
var config = {
headers: {
'Accept':'',
'Content-Type': 'application/json'
}
};
axios.post(url + 'patients', patient, config).then(res =>
{
this.props.dispatch(addPatientAction(patient));
})
.catch( function(error) {
console.log(JSON.stringify(error, null, 2));
});
}
我如何将商店与道具连接:
@connect((store) => {
return {
patients: store.PatientsReducer.patients
}
})
export default class RegistratePatient extends React.Component {
constructor(props) {
super(props);
this.handleAddPatientClick = this.handleAddPatientClick.bind(this);
// constructor code
}
handleAddPatientClick(patient) {
// code above
}
render() {
// render code
}
}
答案 0 :(得分:0)
试试这个
const PatientsReducer = (state = patientsInitialState, action) => {
switch(action.type) {
// other not related cases
case 'ADD_PATIENT':
return Object.assign({}, state, {patients:[...state.patients,action.payload]})
default:
return state;
}
}