2017-02-09 4 views
0

redux 상태에서 요소를 제거 할 때 구성 요소를 업데이트하는 데 문제가 있습니다.redux 상태를 변경할 때 요소 제거

내 구성 요소 :

const mapStateToProps = state => ({ 
    products: state.shoppingBasket.list, 
}); 

const ShoppingBasket = React.createClass({ 
    propTypes: { 
    removeProduct: React.PropTypes.func.isRequired, 
    products: React.PropTypes.array, 
    open: React.PropTypes.func.isRequired, 
    }, 
    removeFromBasket(index, name) { 
    this.props.removeProduct(index); 
    }, 
    render() { 
    return (
     <div> 
     {this.props.products.map((product, index) => (
       <div key={index}> 
       product.name 
       <button onClick={() => this.RemoveFromBasket(index)} 
       </div> 
      ); 
     )} 
     </div> 
    ); 
    }, 
}); 

export default connect(mapStateToProps, actions)(ShoppingBasket); 

내 감속기 :

export default function shoppingBasket(
    state = { 
    list: [], 
    }, 
    action 
) { 
    let tmp = []; 
    switch (action.type) { 
    case SHOPPING_BASKET_ADD: 
     return { list: [...state.list, action.payload.product] }; 
    case SHOPPING_BASKET_REMOVE: 
     tmp = state.list; 
     tmp.splice(action.payload.index, 1); 
     return { list: tmp }; 
    default: 
     return state; 
    } 
} 

REDUX 상태에서 삽입 요소 내 구성 요소 successfuly 업데이트,하지만 난 버튼을 클릭 removeFromBasket 요소를 호출 할 때 REDUX 상태에서 제거되었다 하지만위원회는 업데이트하지 말아야한다.

답변

1

splice은 새 배열을 반환하지 않지만 호출 한 배열 만 변형하므로 list 속성은 변경되지 않습니다. Redux에서 항상 새로운 상태 객체를 반환해야합니다 (변경되지 않은 상태). 그렇지 않으면 내부적으로 현재 속성과 다음 속성의 얕은 비교를 수행하므로 참조가 변경되지 않으면 요소를 동일하게 간주하고 구성 요소를 다시 렌더링하지 않기 때문에 구성 요소가 업데이트되지 않습니다. 당신은 이런 Redux way에 배열 프론트 항목을 제거 할 수 있습니다

case SHOPPING_BASKET_REMOVE: 
     return { list: [ 
     ...state.list.slice(0, action.payload.index), 
     ...state.list.slice(action.payload.index + 1) 
     ] 
    } 
+0

감사합니다, 또한 작업과'반환 {목록 : _ ((I를 state.list.filter) => 내가 == action.payload!. 색인)};' –

관련 문제