我确定我已经使事情复杂化了,但是我有一个应用程序可以抓取用户凭据,然后执行网络身份验证以检索sessionID。我获取此会话ID并将其保存在我的应用上下文中,以便所有需要sessionID的Web组件都可以调用上下文。
我在尝试以某种方式找出状态时遇到了问题,该方式允许我在呈现Web组件之前等待SessionID填充完毕。
我尝试了各种条件渲染技术,但显然我是个白痴哈哈。
import React from "react";
import {Bar} from 'react-chartjs-2';
import Draggable from 'react-draggable';
import './FetchEndpoints.css'
import { AppContext } from "../../context/AppContext";
export default class FetchEndpoints extends React.Component {
static contextType = AppContext
state = {
loading: true,
dreturn: null,
render: false
};
async componentDidMount(){
const {session} = this.context
const url = "https://portal.local";
let headers = new Headers();
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
headers.set('session', session);
console.log(session)
const response = await fetch(url,{method:'POST',
headers: headers
});
const r_data = await response.json();;
this.setState({
loading: false,
chartData : {
datasets:[
{
label: 'Endpoints',
backgroundColor: [
'rgba(255,99,132,0.2)',
'rgba(54,162,235,0.2)',
'rgba(255,206,86,0.2)',
'rgba(75,192,192,0.2)'
],
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [r_data.info.data.total, r_data.info.data.unmanaged,r_data.info.data.managed,r_data.info.data.unmanageable]
}
]
}
})
}
render() {
if (this.state.loading) {
return( <h1>...loading</h1>)
}
return (
<Draggable
handle=".handle"
defaultPosition={{x: 0, y: 0}}
position={null}
grid={[25, 25]}
scale={1}
onStart={this.handleStart}
onDrag={this.handleDrag}
onStop={this.handleStop}>
<div className="handle">
<div>
<div className="EndpointBox">
<div className = 'chart'>
<Bar
data={this.state.chartData}
width={600}
height={200}
options={{
maintainAspectRatio: false,
title: {
display:true,
text:'Discovered Interfaces',
fontSize:15
},
legend:{
display:false
}
}}
/>
</div>
</div>
</div>
</div>
</Draggable>
);
}
}```
The session from AppContext renders after the above has already ran. I would like to set something up so that it would if session is null wait for session to not be null.
答案 0 :(得分:1)
您可能应该将componentDidMount
中包含的逻辑移至单独的函数-例如fetchCartData
。
然后,您可以执行以下操作:
async componentDidMount() {
if(this.context.session !== null) {
this.fetchChartData();
};
}
async componentDidUpdate() {
if(this.context.session !== null) {
this.fetchChartData();
};
}