0

我正在使用 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>
           )
}
4

1 回答 1

1

如果你必须从 API 或类似的地方加载任何数据,你应该在componentDidMount里面做

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

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

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

如果您必须更新父级:

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

如果它在同一个组件中

.then(res=>res.json())
.then(res => this.setState({ user: res })
于 2018-12-16T12:56:44.710 回答