问题
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?
Everywhere else I use this.setState it works. The full code can be found on this link.
回答1:
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)
}
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.
回答2:
try something like this
this.setState(function(state, props) {
return {
...state,
roleSelected: true,
roleSelectedId: record.key
};
});
来源:https://stackoverflow.com/questions/60136066/this-setstate-not-updating-state