【问题标题】:Render Component every time it's get clicked每次点击时渲染组件
【发布时间】:2019-08-24 23:30:24
【问题描述】:

我有一个显示名称和 ID 的国家/地区列表。 我希望能够编辑国家,所以我为每一行添加了编辑按钮。组件的结构是这样的:

ListComponent
 -- Edit Component // will show a modal
 --- Modal Component
 ---- Form Component

我应该在模式打开时填写表格,现在问题是: 我应该使用哪种生命周期方法来填写表格?

componentDidMount 只触发一次。

componentDidUpdate 不会在第一次调用时触发,而是在之后触发。

代码:

  componentDidMount(prevProps, prevState) {
      if(this.props.status == 'update') {
        this.props.form.setFieldsValue({
          isForeign: this.props.country.isForeign,
          name: this.props.country.name,
        });
      }
  }

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    如果你想在一个类组件中处理启动和更新,你必须同时使用这两种生命周期方法。这是 React 为功能组件实现钩子以避免冗余的一个重要原因。

    https://reactjs.org/docs/hooks-intro.html

    【讨论】:

    • 你对这种东西有什么建议吗?
    • 尝试在 componentDidUpdate 中重复您的代码。不过,从父组件控制此表单似乎会更好。在父组件中,您可以简单地使用状态来控制这一切,而不必检查带有生命周期的道具,然后对父组件进行回调。
    【解决方案2】:

    您可以使用componentWillReceiveProps

    componentWillReceiveProps: 当特定的 prop 更新到时执行 触发状态转换。

    我的代码库中的小例子

       componentWillReceiveProps(nextProps) {
                if (this.props.userId !== nextProps.userId) {
                        const url = `${ROLE_API}/${nextProps.userId}`;
                        Get(url).then(res => {
                                this.setState({rolesName: res.data.rolesName, 
                                 currentUserRoles: res.data.currentUserRoles,
                                 userId: res.data.userId});
                        });
                }
        }
    

    【讨论】:

    • 感谢您的建议,但第一次点击它不会触发,但第二次点击它就会触发
    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2022-11-15
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多