Redux:如何将父道具传递给reducer的初始状态?

时间:2017-08-03 16:47:58

标签: reactjs redux react-redux

好的,这让我烦恼!在反应中,我有一个Test组件接收道具来创建它的初始状态,如下所示:

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

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

尝试在redux中执行此操作,我有以下reducer:

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

如何在此处设置initialState,使用由其父级提供给测试组件的props?或者有更好的方法吗?

干杯!

1 个答案:

答案 0 :(得分:2)

我不会将这些物品作为道具发送给父亲,而是我将物品从父亲发送到redux并使用连接在儿子接收它们。

代码说明: - 你在构造函数中收到道具, - 使用操作将项目发送到redux - 接收他们作为道具 - 使用道具来渲染项目

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);