【发布时间】:2017-03-21 10:47:52
【问题描述】:
我是 React 新手,所以很可能有更好的方法来解决我正在尝试做的事情。
我正在使用 React 和 Redux 通过单击按钮从 JSON 文件中提取 HTML sn-p 并将其插入到 TemplateContent 组件中。
我遇到的问题是,如果我在该行中单击两次按钮,我希望将 sn-p 插入两次,但由于我通过检查 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 文件的方式
-
如果他们都有相同的ID,你的逻辑如何运作?还有一件事,你为什么要从
json文件中加载html内容?