在POST请求的响应中,我获得了以下JSON数据,
{"chart":
{
"data":[
{
"x": [0, 1, 2, 3, 4, 5, 6, 7, 8],
"y": [0, 3, 6, 4, 5, 2, 3, 5, 4],
"type": "scatter",
"name":"Plot 1"
},
{
"x": [0, 1, 2, 3, 4, 5, 6, 7, 8],
"y": [0, 4, 7, 8, 3, 6, 3, 3, 4],
"type": "scatter",
"name":"Plot 2"
},
{
"x": [0, 1, 2, 3, 4, 5, 6, 7, 8],
"y": [0, 5, 3, 10, 5.33, 2.24, 4.4, 5.1, 7.2],
"type": "scatter",
"name":"Plot 3"
}
],
"layout":{
"showlegend": true,
"legend": {"orientation": "h"}
}
}
}
现在,我得到了响应,但无法按预期绘制图形。以下是我到目前为止编写的js代码,
const dataForPost = {
dataset_id: 1,
features: [],
analysis_level: 1
};
export default function DomainAssesment(){
const [graphData, setGraphData] = useState('');
const postData = (event) => {
axios.post('http://localhost:5000/Plot', dataForPost)
.then((response) =>{
setGraphData(response.data.chart);
console.log(graphData);
});
}
return (
<Container>
<Button className="success" onClick={postData}>Get Graph</Button>
<Plot data={graphData.data} layout={graphData.layout} />
</Container>
);
}
控制台日志中的结果是这样的,
任何意见或建议将不胜感激。
最佳答案
使用response.data对象编写逻辑。使用您的UI模型映射response.data.object,然后更新react组件的状态,最终将调用render方法再次渲染组件。请参见下面的示例。
private getBoardings = () => {
const uri = "YOUR_URL"; //get or post whatever it is
trackPromise(
this._ajaxhelper.get(uri,
(response) => { this.listOnboardingSuccess(response); },
(error) => { this.listOnboardingFailure(error); }));
}
private listOnboardingSuccess(response: any) {
const boardings = [] as IboardingContext[];
response.data.boardings.map((boarding: any) => {
if (boarding != null) {
boardings = this.OnboardingMapping(boarding); //mapping of response
}
});
this.setState({ boards: [...boards], loading: false }); //Update state here
}
关于javascript - 如何提取从API获取的JSON数据并传递到react-plotly中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61492138/