[英]React - using Context to pass down array variable, but when there is an update, component receiving array variable not re-render
[英]Render only when Context variable is not null REACT
我確定我已經使事情復雜化了,但是我有一個可以獲取用戶憑據的應用程序,此時它會執行Web身份驗證來檢索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.
您可能應該將componentDidMount
包含的邏輯移至單獨的函數-例如fetchCartData
。
然后,您可以實現以下內容:
async componentDidMount() {
if(this.context.session !== null) {
this.fetchChartData();
};
}
async componentDidUpdate() {
if(this.context.session !== null) {
this.fetchChartData();
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.