【发布时间】:2017-08-24 04:24:19
【问题描述】:
我不明白如何让数组通过 combinereducers 传递。
动作发送后,我想将输入文本与数组连接。(state d)
redux 站点中的一个示例如下,在 reducer 中,我确实喜欢它。(checkD_E 函数)
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
completed: false
}
]
})
d 始终只更新以连接未定义和最后输入的文本。
第一个“未定义”是由于没有读取 initialState 引起的。(const initialState 变量)
const ADD_TODO = 'ADD_TODO'
const BDD_TODO = 'BDD_TODO'
const DDD_TODO = 'DDD_TODO'
const EDD_TODO = 'EDD_TODO'
const {PropTypes} = React;
const {createStore,combineReducers} = Redux;
const { Provider, connect} = ReactRedux;
let store = createStore(rootReducer)
function changeA(text) {
return { type: ADD_TODO, text }
}
function changeB(text) {
return { type: BDD_TODO, text }
}
function changeD(text) {
return { type: DDD_TODO, text }
}
function changeE(text) {
return { type: EDD_TODO, text }
}
function checkA_B(state={},action){
switch (action.type) {
case ADD_TODO:
return Object.assign({}, state.checkA_B, {a:action.text})
case BDD_TODO:
return Object.assign({}, state.checkA_B, {b:action.text})
case DDD_TODO:
return state
default:
return state
}
}
function checkD_E(state=[],action){
switch (action.type) {
case DDD_TODO:
return Object.assign({}, state,{
d: [...state.d,action.text]
} )
case EDD_TODO:
return Object.assign({}, state, {e:action.text})
default:
return state
const initialState ={
a:"aaa",b:"bbb",c:"ccc",d:[],e:"eee"
}
function rootReducer(state = initialState,action){
return {
checkA_B:checkA_B(state,action),
checkD_E:checkD_E(state,action)
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {a:props.a,b:props.b,d:props.d,e:props.e,inputText:props.inputText,onClick:props.onClick};
this.onInput = this.onInput.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onInput(e){
this.setState({inputText:e.target.value})
}
onSubmit(e){
e.preventDefault()
this.state.onClick(this.state.inputText)
this.setState({inputText:""})
}
render() {
return (
<div>
<form onSubmit={this.onSubmit}>
<input value={this.state.inputText} onChange={this.onInput} />
<button type="submit">Add Todo</button>
</form>
<label>{console.log(this.props.d.map(x=>return x))}</label><label>{this.state.b}</label><label>{this.state.c}</label>
</div>
);
}
}
Clock.propTypes = {
inputText:PropTypes.string.isRequired,
onClick:PropTypes.func.isRequired,
a:PropTypes.string.isRequired,
b:PropTypes.string.isRequired,
d:PropTypes.array.isRequired,
e:PropTypes.string.isRequired
}
function mapDispatchToProps(dispatch){
return {onClick:(x)=>{
dispatch(changeD(x))
}
}
}
function mapStateToProps(state,ownProps){
return {d:state.checkD_E.d}
}
Clock = connect(mapStateToProps,mapDispatchToProps)(Clock)
ReactDOM.render(
<Provider store={store}><Clock /></Provider>,
document.getElementById('root')
);
index.html
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
我猜 mapStatetoProps 中的返回值必须更改。
但我不知道。
【问题讨论】:
标签: arrays reactjs redux react-redux