我是新手反应redux,我必须设计一个带有单选按钮的基本表单。提交后,我想将结果传递给reducer并更新状态。我对redux感到困惑,如何更新状态,初始化状态,以便我可以调用初始状态的减速器。
我不熟悉redux-forms,我必须先做app而不使用redux-forms。
到目前为止,我已经这样做了:
import React, { Component } from 'react';
import './App.css';
import { createStore } from 'redux';
const hobby = [{
"id": 1,
"text": "Sports",
"answers": [{
"id": 1,
"text": "Badminton",
"responses": 5
}, {
"id": 2,
"text": "Swimming",
"responses": 15
}]
},
{
"id": 2,
"text": "Grocery",
"answers": [{
"id": 1,
"text": "Bread",
"responses": 10
}, {
"id": 2,
"text": "Cheeze",
"responses": 5
}]
}
];
function hobbyReducer(state, action) {
if(action.type === "SUBMIT"){
hobby.map((e)=>{
if(e.id == action.id){
e.answers.map((i)=>{
if(i.text === action.text){
// I think I have to use Object.assign({}, state, {data to be written for update responses count})
// Here I have to update the state with increamented value for i.responses
// Suppose I choose badminton then i.responses = 15 should be now 16
// return updated state
}
})
}
})
}
}
class App extends Component {
constructor(){
super();
this.state ={
}
}
handleSubmit(e){
const store = createStore(hobbyReducer); // created store here
var k = (document.querySelector('input[name = "hobby"]:checked').value);
store.dispatch({type:"SUBMIT", text: k, id: 1}); // Dispatching action to reducer
store.subscribe(()=>{
console.log(store.getState());
});
}
render() {
return (
<div className="App">
<form onSubmit={this.handleSubmit.bind(this)}>
<input type="radio" value="Badminton" name="hobby" /> Badminton
<input type="radio" value="Swimming" name="hobby" /> Swimming
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default App;