I need to solve the following problem: User change select input -> ajax request to server -> response is array of objects like {type: "img", name: "background", etc} -> depending on this response I need to create array of fields with different components(depending on type). I try to write own reducer to change state of form, but in my reducer state is always empty(
index.js
const rootReducer = combineReducers({
landing: reducers,
form: formReducer
})
const store = createStore(
rootReducer,
{},
composeWithDevTools(applyMiddleware(thunk))
)
const form = document.getElementById('form')
ReactDOM.render(
<Provider store={store}>
<EditForm landing={landing} />
</Provider>,
form
)
EditForm.js
import * as formActions from './actions'
class EditForm extends React.Component {
constructor(props) {
super(props)
let { landing, initializeLanding } = this.props
initializeLanding(landing)
this.handleSubmit = this.handleSubmit.bind(this)
this.handleTemplateSelect = this.handleTemplateSelect.bind(this)
}
handleTemplateSelect(e) {
this.props.actions.getVars(e.target.value)
}
handleSubmit(values) {
...
}
render() {
return (
<LandingForm
onSubmit={this.handleSubmit}
handleTemplateSelect={this.handleTemplateSelect}
/>
)
}
}
const mapDispatchToProps = dispatch => {
return {
initializeLanding: function(form) {
dispatch(initialize('adminLandingForm', form))
},
actions: bindActionCreators(formActions, dispatch)
}
}
const mapStateToProps = state => {
return state.form.adminLandingForm
}
EditForm = reduxForm({
form: 'adminLandingForm'
})(EditForm)
export default connect(mapStateToProps, mapDispatchToProps)(EditForm)
actions.js
const SET_VARS = 'admin-landing-from/SET_VARS'
export const getTracks = template => dispatch => {
return fetch(url)
.then(response => {
return response.json()
})
.then(json => {
dispatch({ type: SET_VARS, vars: json.data })
})
}
reducers.js
const SET_VARS = 'admin-landing-from/SET_VARS'
const reducers = (state = {}, action) => {
switch (action.type) {
case SET_VARS:
console.log(state) --> Always empty
return {
vars: action.vars
}
default:
return state
}
}
答案 0 :(得分:0)
Try
const reducers = (state = {}, action) => {
switch (action.type) {
case SET_VARS:
console.log(state) --> Always empty
return {
...state,
vars: action.vars
}
default:
return state
}
}
答案 1 :(得分:0)
我认为,你的问题是你定义了两次const SET_VARS。只需在 Reducer 中尝试定义一次,然后将 SET_VARS 导入操作。
因为州默认= {} =&gt;总是你有空对象:)