【问题标题】:Reactjs rerender component after CRUD OperationCRUD 操作后 Reactjs 重新渲染组件
【发布时间】:2018-12-16 12:41:50
【问题描述】:

我正在使用 MongoDB 作为托管在 heroku 上的数据库来构建登录。 我想在我的数据库中更新我的登录用户的属性后更改我的组件的值。

这是我更新用户“信用”的函数:

//ProgressMobileStepper.js

updateCredits() {
      fetch('https://mighty-pigeon-8369.herokuapp.com/users/5', {
      method: 'put',
      headers: {
        ...authHeader(),
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({credits: 20})
    }).then(res=>res.json())
      .then(res => console.log(res))


    }

它被同一文件中按钮的 onClick 事件触发!

这是我的组件(其他文件),它应该在更新我的用户的信用后立即重新呈现工具栏:

//ItemViewAll.js

  <Toolbar style={{background: '#ffffff', color: '#000'}}>
          <IconButton
            color="inherit"
             onClick={this.handleClose}
             style={{outline: 'none'}}
          >
          <CloseIcon onClick={this.handleClose}/>
          </IconButton>


         {user && user.token &&
            <Button variant="outlined">
               {user.credits}
             </Button>

         }

        </Toolbar>

这是用户的json(不知道是否有帮助):

//MongoDB

{
    "credits": 20,
    "_id": "5c13fd6008dd3400169867a5",
    "firstName": "Martin",
    "lastName": "Seubert",
    "username": "admin",
    "createdDate": "2018-12-14T18:58:40.295Z",
    "__v": 0,
    "id": "5c13fd6008dd3400169867a5"
}

如果您对在ItemViewAll.js的工具栏中单击按钮更新我的用户积分后如何更改渲染有任何建议,我将非常感谢!

干杯,圣诞快乐!

马丁

编辑

这是我的子组件与工具栏的渲染:

render() {

      const { classes } = this.props;
      let user = JSON.parse(localStorage.getItem('user'));
         return(
               ...
                 <Toolbar style={{background: '#ffffff', color: '#000'}}>
          <IconButton
            color="inherit"
             onClick={this.handleClose}
             style={{outline: 'none'}}
          >
          <CloseIcon onClick={this.handleClose}/>
          </IconButton>


         {user && user.token &&
            <Button variant="outlined">
               {user.credits}
             </Button>

         }

        </Toolbar>
           )
}

【问题讨论】:

  • 渲染中的用户对象来自哪里。还需要用updateCredits的回复还是不用
  • @ShubhamKhatri 感谢您的重播。我为你编辑了我的帖子。

标签: javascript reactjs mongodb crud react-lifecycle


【解决方案1】:

如果你必须从 API 或类似的地方加载任何数据,你应该在 componentDidMount 中进行操作

除此之外,很难通过您提供的组件层次结构(组合)的示例来判断。

无论如何,如果您的子组件必须更新父组件,您必须将方法作为 prop 从父组件传递给子组件,并通过调用将子组件中加载的数据传递给父组件你传递的那个道具。

如果您必须首先更新您从中获取数据的相同组件,只需在获取数据后调用 this.setState。

如果您必须更新父级:

.then(res=>res.json())
.then(res => this.props.methodPassedFromParent(res))

如果在同一个组件中

.then(res=>res.json())
.then(res => this.setState({ user: res })

【讨论】:

  • 感谢ypur的帮助,我会先尝试在同一个组件中实现解决方案,然后再尝试更新父组件。
猜你喜欢
  • 2023-04-11
  • 2020-06-20
  • 2021-12-06
  • 2019-01-01
  • 2018-10-28
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多