javascript - 如何提取从API获取的JSON数据并传递到react-plotly?

标签 javascript html css reactjs

在 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>
    );

}

控制台日志中的结果是这样的, enter image description here

任何形式的意见或建议将不胜感激。

最佳答案

使用response.data对象编写逻辑。将 response.data.object 与您的 UI 模型映射,然后更新 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/

相关文章:

javascript - 通过 jquery 创建的 <div> 未设置样式

javascript - 如何使用 getMetaProperty 或访问商店中的元数据?

javascript - 链接未添加到所有图像之前

Javascript 选项更改头部 style.css

javascript - 在 jVectorMap 上的一些圆圈标记上放置不同的描边颜色和宽度

javascript - 如何自动水平滚动到div内的中间?

javascript - 当一个 div block 被触摸并且在同一条线上时,我如何将一个 div block 放在另一个垂直排列的下方?

javascript - 简单的 Javascript 更新 HTML 中的长计算进度

javascript - 禁用或启用下拉选择上的复选框

javascript - 从 angularJS 中的 JSON 数组获取数据