2017-08-03 43 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); 
相關問題