2017-02-18 333 views
0

我想問一下您對此的看法。基本上我現在想要的是在刪除對象列表中的項目後刷新組件列表。目前,我可以通過deleteHeroes(list,index)函數成功刪除一個項目,但我的組件根本不刷新以反映刪除的項目。你能否介紹一下我該怎麼做?這裏是我的代碼如下:刪除對象後刷新組件 - ReactJS

componentDidMount(){ 
    // Fetch lists of heroes 
    this.props.getAllHeroes(); 
} 

renderHeroesList(){ 
    var listData = this.props.heroes.map((heroes,index) => (
     <HeroesListComponent key={heroes.id} heroes={heroes} onDelete = {() => this.deleteHeroes(heroes,index)} /> 
    )); 

    return listData; 
} 

// Remove item on heroes list 
deleteHeroes(list,index){ 
    const heroesProps = this.props.heroes; 
    heroesProps.splice(heroesProps.indexOf(index), 1); 
} 

render(){ 

    return(
     { this.renderHeroesList() } 
    ); 


function mapStateToProps(state){ 
    return { 
     heroes: state.heroes.data 
    } 
}} 
function mapDispatchToProps(dispatch){ 
    return bindActionCreators ({ 
     getAllHeroes: getAllHeroes, 
     deleteHero: deleteHero, 
    }, dispatch); 
} 

回答

0

因爲你沒有通知任何關於你的改變。

您必須派遣deleteHeroes之後的動作,這樣

deleteHeroes(list,index){ 
    const { heroesProps, dispatch }= this.props; 
    heroesProps.splice(heroesProps.indexOf(index), 1); 
    dispatch({type: 'SAVE_HEROES', heroes: heroesProps}); 
} 

// and somewhere in reducer 
case SAVE_HEROES: 
    return {...state, heroes: action.heroes} 

東西,編寫相應的函數來減速。 但讓組件刪除hereos(改變狀態),你打破了redux的想法。

取而代之的是,組件不應該直接修改英雄,而是派遣類似'DELETE_HEROES'的動作並讓其他人完成。

+0

我按照你的指示,派遣deleteHeroes()之後的動作,但我weirded爲什麼渲染方法不會觸發,即使是redux改變英雄列表的狀態。 –

0

你必須要考慮兩個主要選擇:

  1. 把數據(的狀態),以共同的祖先,那就是標準戰略,從反應:https://facebook.github.io/react/docs/lifting-state-up.html

  2. 把所有的狀態,終極版( https://github.com/reactjs/react-redux),然後根據redux狀態連接你的組件和顯示器。這種情況下,你不必須做任何事情刪除,終極版框架後,將負責數據流和用戶界面的刷新

+0

我目前正在做第二個,但現在即使狀態改變,渲染方法沒有解僱我現在遇到的問題 –

1

您有副作用,應不惜一切代價避免。就你而言,這是你在改變道具的內部參考heroes。所以避免這個問題的典型計劃是克隆道具,然後用新的道具數據派發新的動作。所以,你的代碼應該是這樣的:

deleteHeroes(list,index){ 
    const clonedHeroesProps = this.props.heroes.slice(0); // clone the array 
    heroesProps.splice(heroesProps.indexOf(index), 1); 
    dispatch({type: 'SAVE_HEROES', heroes: clonedHeroesProps}); 
} 

的更好,更Reactish的方法是通過使用Immutability Helpers

deleteHeroes(list,index){ 
    const clonedHeroesProps = update(heroesProps, {$splice: [[heroesProps.indexOf(index), 1]]}); 
    dispatch({type: 'SAVE_HEROES', heroes: clonedHeroesProps}); 
} 
+0

是的,我已經做到了這一點,併成功派遣給我更新的英雄。我現在的問題是我的組件在我收到更新的英雄列表 –

+0

後沒有反應,你可以嘗試用'componentWillReceiveProps(nextProps)'方法調試這個,在那裏檢查你是否獲得了新的道具。同時查看React開發工具在整個過程中與道具和狀態有什麼關係。 – Shota

+0

componentWillReceiveProps不會觸發,但是當我將控制檯登錄到renderHeroesList()內時,我可以看到this.props.heroes基於通過deleteHeroes刪除的項目進行更改。但即使renderHeroesList()發生了變化,渲染方法仍然不會啓動。 –