【问题标题】:Reactjs - componentWillReceiveProps on button click - fails when button clicked twiceReactjs-单击按钮时的componentWillReceiveProps-单击两次按钮时失败
【发布时间】: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 内容?

标签: reactjs redux


【解决方案1】:

如果你对多个模块没问题,我建议你不要用它作为重新渲染或不重新渲染的条件。您可以随时使用虚拟道具来更改自己的喜好,因为您使用的是 redux,这不会有问题。

通过在点击时调度动作,dispatch({ type: INCREMENT }) 并拥有一个匹配该动作的减速器,添加 ++int 或任何随机的东西都可以。

那么你将不得不使用它作为 nextProps 的条件

mapStateToProps = ({ counter }) =&gt; ({ ...counter })

nextProps.counter !== this.props.counter

我认为你已经准备好了。

【讨论】:

    【解决方案2】:

    试试这个条件:

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

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 1970-01-01
      • 2021-06-27
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多