我是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))
讓我知道如果你需要什麼,我試圖實現任何額外的代碼或進一步的解釋。
任何幫助將不勝感激! :)
那些是兩個模塊'ids'同樣這是在連續取? –
是的,多數民衆贊成在查找json文件 – Majki
如果他們都有相同的ID,你的邏輯怎麼可能工作?還有一件事你爲什麼要從'json'文件加載'html'內容? –