CRUD操作后,Reactjs重新呈现组件

时间:2018-12-16 12:41:50

标签: javascript reactjs mongodb crud react-lifecycle

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

1 个答案:

答案 0 :(得分:1)

如果您必须从API或类似文件中加载任何数据,则应在componentDidMount内进行

此外,很难通过示例说明您提供了组件的层次结构(组成)。

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

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

如果必须更新父项:

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

如果在同一组件中

.then(res=>res.json())
.then(res => this.setState({ user: res })
相关问题