状态的变化不会在道具中传播

时间:2017-10-15 10:16:12

标签: reactjs redux

我有"经典" React redux的问题是当我尝试在组件中访问它时,没有将state中的更改传播到props

Here我读过那个

  

99.9%的时间,这是因为你不小心改变了数据,通常在你的减速器中

你能告诉我我做错了什么吗?这是如何在数组中对指定对象的属性进行深层复制的好方法吗?

注意:在return语句的reducer中,状态显然已正确更改(调试它)

减速机:

case 'TOGGLE_SELECTED_TAG':
        const toggledTagId = action.payload;

        const index = findItemById(state.tags, toggledTagId);
        const newTags = state.tags.slice(0);
        if(index >= 0)
        {
            newTags[index] = Object.assign(
                state.tags[index], 
                {selected: !state.tags[index].selected});

            state.tags = newTags;
        }

        return Object.assign({}, state);

组件:

import React from 'react';
import { Button, FormControl, Table, Modal } from 'react-bootstrap';
import { connect } from 'react-redux';
import axios from 'axios';

import {selectTagAction} from '../../actions/actions'

@connect((store) => {
return {
    tags: store.TagsReducer.tags,
}
})

export default class AssignTag extends React.Component {
constructor(props) {
    super(props);

    this.handleTagClick = this.handleTagClick.bind(this);
}

handleTagClick(element) {
    debugger;
    this.props.dispatch(selectTagAction(element));
}

 render() {
    const tags = this.props.tags;
    console.log(tags);
    const mappedTags = tags.map(tag => {
        return (
            <div className="col-sm-12" key={tag.id} onClick={() => this.handleTagClick(tag.id)}
                style={{background: this.getBackgroundColor(tag.selected)}}>
                <span>{tag.name}</span>
            </div>
        )
    })

// code continues
}

}

2 个答案:

答案 0 :(得分:1)

你确实正在改变国家。试试这个:

case 'TOGGLE_SELECTED_TAG':
        const toggledTagId = action.payload;
        const index = findItemById(state.tags, toggledTagId);
        let newTags = state;
        if( index >= 0 )
        {
            newTags[index] = Object.assign(
                {},
                state.tags[index],
                { selected: !state.tags[index].selected }
              );
            //state.tags = newTags;   This line essentially mutates the state
            return Object.assign( {}, state, { tags: newTags });
        }

        return state;

答案 1 :(得分:0)

避免状态突变的另一个解决方法是在reducer中使用ES6速记:

....   return { ...state, tags : newTags };