2017-03-21 74 views
0

我是React的新手,所以很有可能有更好的方法來實現我想要做的事情。Reactjs - 按鈕點擊時的componentWillReceiveProps - 按鈕點擊兩次後失敗

我正在使用React和Redux從JSON文件中拉取HTML片段,然後將它插入到TemplateContent組件中。

我遇到的問題是,如果我在該行單擊按鈕兩次,我想要插入兩次片段,但由於我通過檢查nextProps和this.props阻止componentWillReceiveProps中的循環匹配它不起作用,到目前爲止,我還沒有很幸運地找到解決方法。

這是我的代碼...

class TemplateContentContainer extends Component { 
    constructor() { 
     super() 

     this.fetchModule = this.fetchModule.bind(this) 
     this.removeModule = this.removeModule.bind(this) 
    } 

    componentWillReceiveProps(nextProps) { 
     if(nextProps.addedModule !== this.props.addedModule) // prevent infinite loop 
     this.fetchModule(nextProps.addedModule) 
    } 

    fetchModule(id) { 
     api 
      .getModule(id) 
      .then((module) => { 
       this.props.dispatch(actions.receiveModule(module)) 
      }) 
      .catch((err) => { 
       console.log('TemplateContainer Error: ' + err) 
      }) 
    } 

    removeModule(module) { 
     this.dispatch(actions.removeModule(module)) 
    } 

    render() { 
     return (
      <TemplateContent 
       templateModules={this.props.templateModules} 
       removeModule={this.removeModule} 
      /> 
     ) 
    } 
} 

const mapStateToProps = (state) => ({ 
    templateModules: state.receiveModuleById, 
    addedModule: state.addModuleById, //returns id of added module - add me clicked 
}) 

const mapDispatchToProps = (dispatch) => ({ 
    dispatch 
}) 

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(withRouter(TemplateContentContainer)) 

讓我知道如果你需要什麼,我試圖實現任何額外的代碼或進一步的解釋。

任何幫助將不勝感激! :)

+0

那些是兩個模塊'ids'同樣這是在連續取? –

+0

是的,多數民衆贊成在查找json文件 – Majki

+0

如果他們都有相同的ID,你的邏輯怎麼可能工作?還有一件事你爲什麼要從'json'文件加載'html'內容? –

回答

0

如果您對多個模塊沒問題,我建議您不要將其用作重新呈現的條件。你可以隨時使用虛擬道具來改變你的喜好,因爲你使用的是redux,這不會是一個問題。

通過點擊調度動作,dispatch({ type: INCREMENT })並有一個與該動作相匹配的縮減器,或者添加++ int或任何隨機的東西都可以。

,那麼你將不得不使用它作爲條件的nextProps

mapStateToProps = ({ counter }) => ({ ...counter })

nextProps.counter !== this.props.counter

,並與我想你都設置。

+0

完美!工作,非常感謝:) – Majki

0

嘗試這種情況:

componentWillReceiveProps(nextProps) { 
    if(nextProps.templateModules !== this.props.templateModules) 
    this.fetchModule(nextProps.addedModule) 
}