2017-08-03 102 views
0

好吧,这是窃听我!在反应我有一个测试组件接收的道具来创建它的初始状态,例如:Redux:如何将父项道具传递给reducer的初始状态?

constructor(props) { 
    super(props) 
    const {items} = this.props 
    this.state = { 
     items: {...items}, 
     score: 0 
    } 
} 

传递给它的项目(其成为的状态的一部分)是项测试 - 它开始删除这些项目时,他们已经过测试,直到state.items为空 - 测试完成。

试图做到这一点的终极版,我有以下减速器:

import * as types from '../actions/action-types' 
import Store from '../Store' 

const initialState = { 
    items: {},// I want items to contain the props passed to this component 
    score: 0 
} 

const testWrapperReducer = function(state = initialState, action) { 
    let newState = null 
    switch(action.type) { 
     case types.QUESTION_ANSWERED: { 
      let {items, score} = state 
      delete items[action.english] 
      score += action.isCorrect 
      newState = {...state, items, score} 
      break 
     } 
     default: 
      newState = state 
    } 

    return newState 
} 

export default testWrapperReducer 

如何设置初始化状态这里,利用给其父测试组件的道具?还是有更好的方法来做到这一点?

干杯!

+0

你应该终极版创建一个golabal商店,而不是将道具传递给您可以调用的组件并采取行动更新redux商店,并使用redux的连接功能将子组件连接到商店 –

+0

通常情况下,您将数据加载到然后使用'connect'将数据作为道具发送给组件;) – Crysfel

回答

1

我不会从父亲那里发送道具作为道具,相反我会从父亲的项目发送到REDX并使用连接接收他们的儿子。

代码解释: - 您收到的道具在构造函数中, - 使用动作 发送物品终极版 - 接纳他们为道具 - 使用道具来呈现项目

import React, { PropTypes, Component } from 'react'; 
import { connect } from 'react-redux'; 
import * as actions from '../actions'; 

const Item = (props) => { 
    <div>{props.item.name}</div> 
} 

class List extends React.Component { 
    constructor(props) { 
    super(props) 
    this.props.setItems(this.props.items) 
    } 
    render() { 
    return (
      <div> 
       {this.props.items.map((item) => { 
        return <Item item={item}></Item> 
       })} 
      </div> 
     ) 
    } 
} 

CreateChat.propTypes = { 
    items: PropTypes.array, 
    setItems: PropTypes.func 
}; 

const mapStateToProps = (state) => { 
    return { 
     items: state.items 
    }; 
}; 

const mapDispatchToProps = (dispatch) => { 
    return { 
     setItems: (items) => dispatch(actions.setItems(items)) 
    }; 
}; 

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(List); 
相关问题