将更新后的状态传递给组件

时间:2016-06-29 16:50:01

标签: reactjs redux react-redux

我在使用React和Redux更新子组件的状态时遇到了一些问题。我是React的新手,所以我可能会以错误的方式解决这个问题。

这基本上是我的用例。 ParentComponent是一个“页面”,它呈现一个自定义的Card组件。 Card组件呈现MyTableComponent组件(fixed-data-table)。我通过“tableData = {this.props.company}”将数据传递给MyTableComponent。 this.props.company是一个对象数组。这些对象包含“名称”attirbute和“users”属性,该属性是与该公司关联的所有用户(从数据库中撤回)的数组。然后该表循环遍历this.props.company并显示数组中的每个公司。

这是我的问题所在。当我单击表中this.props.company列表中的名称时,我将显示与该公司关联的所有用户的列表。现在,它按预期的方式工作,第一次点击,我点击表格中的一个元素,它列出了与该公司相关的正确“用户”。但是,当我返回并从表格列表中点击另一家公司时,我收到与以前相同的用户集。在检查我的日志之后,我看到我的应用程序状态正在成功升级,但我的MyTableComponent总是呈现与被点击的previoius公司相关联的用户。即它呈现旧状态而不是新状态。

如何解决此问题?这是组件生命问题吗?我想确保传递到MyTableComponent组件的“this.props.company”是新的更新状态。

编辑 -

我的组件正在更新,它只是更新到以前的状态而不是新状态。我的父组件正在拉入新的正确状态,但它像我的子组件一样,在新状态可以传递到组件之前被呈现。当我尝试运行componentWillReceiveProps(nextProps)时,nextProps是正确的状态。但是this.props.company仍然是旧状态。

class ParentComponent extends Component {

    componentWillMount() {
        this.props.getMyCompanies(this.props.params.id);
    }

    render() {
        return(
            <CardComponent configProps={{ height:'300px', width: '700px'cardItem: <MyTableComponent tableData={this.props.company} /> }} />
        )
    }

}

function mapStateToProps(state) {
    return { company: state.company }
}

export default connect(mapStateToProps, getMyCompanies)(ParentComponent);

减速:

import {
    FETCH_COMPANY,
} from '../actions/types';

const INITIAL_STATE = { company: {} };

export default function(state = { INITIAL_STATE }, action) {
    switch (action.type) {

        case FETCH_COMPANY:
            return {...state, company: action.payload };

        default:
            return state;
    }

}

Root Reducer

import companiesReducer from './companies_reducer';

const rootReducer = combineReducers({
  comapnies: companiesReducer,
});

export default rootReducer;

0 个答案:

没有答案
相关问题