我有个概念上的问题。下面是“伪代码”,其中显示了一个温度预测图表,旁边还有一个按钮。我想让它变成这样,每当点击按钮时,温度预报图就会变成预报降水图,反之亦然。
App.js
import React, { useState } from 'react';
import DataFetcher from './fetch_data.js';
import { graphBuilderTemperature, changeGraph } from './helper_functions.js';
let graphState = "temp";
function App() {
const { weather, forecastWeather } = DataFetcher();
return (
<main>
//(... a bunch of div parents and siblings here)
<div className="forecast_graph">
{graphBuilderTemperature(forecastWeather)}
<button className="forecast_graph_reload" onClick={() => changeGraph(forecastWeather, graphState)}></button>
</div>
</main>
)
}helper_functions.js
//Function that returns a `BarChart` element. From the ReactJs Rechart library for generating charts.
export const graphBuilderTemperature = (forecastWeather) => {
//(...)
return (
<BarChart
//(... temperature forecast chart)
</BarChart>
)
}
export const graphBuilderPrecipitation= (forecastWeather) => {
//(...)
return (
<BarChart
//(... precipitation forecast chart)
</BarChart>
)
}
//function that executes `onClick()` which should change the chart displayed
export const changeGraph = (forecastWeather, graphState) => {
if(graphState === "temp") {
graphState = "precipitation";
return (graphBuilderPrecipitation(forecastWeather));
}else {
graphState = "temp";
return (graphBuilderTemperature(forecastWeather));
}
}当前,代码使用onClick()到达相应的函数调用中,但是每当返回包含新图表的新div元素时,就不会通过react组件App()返回在我的屏幕上显示(更新)。
看来我在这里犯了一些概念上的错误。我不知道如何从onClick()方法返回元素,从主react组件类返回元素。对于代码的不可还原性,事先表示歉意。
有没有人知道我做错了什么,或者我怎样才能实现我所关心的?
发布于 2021-07-29 17:07:49
我认为你的问题是因为你的应用程序没有重新呈现。当应用程序的状态发生变化时,应重新呈现应用程序。
您可以尝试使用useState()来确定需要显示哪种类型的图形,并且您的按钮将在这两种图形类型之间切换。
const [graphType, setGraphType] = useState("temp")
const changeGraph = () => {
graphType === "temp" ? setGraphType("precipitations") : setGraphType("temp")
}然后,在您的App组件中,您想要显示图形,您可以这样做:
{graphType === "temp"? graphBuilderTemperature(forecastWeather) : graphBuilderPrecipitation(forecastWeather) }https://stackoverflow.com/questions/68579853
复制相似问题