this.setState不更新状态 [英] this.setState not updating state
问题描述
由于某些原因,我的this.state
调用没有更新我的roleClicked
函数中的状态.我似乎无法弄清楚问题出在哪里.这是代码:
For some reason my this.state
call is not updating the state in my roleClicked
function. I can't seem to figure out what the problem is. Here is the code:
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom';
import instance from '../../../config/axios';
import ls from 'local-storage';
import Sidenav from '../../layout/Sidenav'
import isLoggedIn from '../../../helpers/isLoggedIn';
import redirectToLogin from '../../../helpers/redirectToLogin';
import apiErrorHandler from '../../../helpers/apiErrorHandler';
import RolesHeader from './RolesHeader';
import '../../../App.css'
import { Table, Pagination, Input, Alert } from 'antd';
export default class ViewRoles extends Component {
state = {
loggedIn: true,
roleSelected: false,
roleSelectedId: null,
rolesTable: {
columns: null,
dataSource: null,
currentPageNumber: null,
currentPageSize: null,
total: null,
},
filters: {
roleName: null
},
displays: {
createRoleView: false,
roleCreatedAlert: false,
},
errors: null
}
componentDidMount = () => {
//here i make AJAX calls to set rolesTables
}
roleClicked = (record) => {
console.log("clicked")
this.setState({
roleSelected: true,
roleSelectedId: record.key
})
}
render() {
if(this.state.roleSelected) {
const roleUrl = "/roles/" + this.state.roleSelectedId
return <Redirect to={roleUrl}/>
}
return (
<React.Fragment>
<Sidenav activeLink="roles"/>
<Table
className="border"
columns={this.state.rolesTable.columns}
dataSource={this.state.rolesTable.dataSource}
pagination={false}
onRow={(record) => {
return {
onClick: () => this.roleClicked(record)
}}}
/>
<Pagination
className="m-3"
current={this.state.rolesTable.currentPageNumber}
pageSize={this.state.rolesTable.currentPageSize}
total={this.state.rolesTable.total}
onChange={this.loadRolesTable}
/>
</React.Fragment>)
}
}
该功能按预期运行,但状态未更新.知道可能是什么问题吗?
The function runs as expected but the state is not updated. Any idea what the problem could be?
我在其他任何地方都使用this.setState可以正常工作.完整代码可在此链接中找到.
Everywhere else I use this.setState it works. The full code can be found on this link.
推荐答案
我更新了roleClicked至此,它起作用了.我仍然不知道为什么初始代码不起作用.
I updated roleClicked to this and it works. I still have no idea why the initial code didn't work.
viewRole = async (record) => {
var currentState = this.state;
currentState.roleSelected = true;
currentState.roleSelectedId = record.key;
await this.setState(currentState);
console.log(this.state)
}
仅将其更改为Async无效.仅将状态分配给currentState
,然后更新currentState
并在setState
中使用它即可.现在,它可以同步和异步运行.
Just changing it to Async didn't work. Only assigning the state to currentState
and then updating currentState
and using it in setState
worked. And now it works both synchronously and asynchronously.
这篇关于this.setState不更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!