我是一个 React-Idiot,更熟悉技术堆栈的其他部分,构建一个超级简单的 React 18 应用程序,包含两个组件:
Home
是调用函数,ImageDisplay
是一个 React 类。我需要它们之间的双向通信。我设法使用属性和状态使其从 Home
向下工作到 ImageDisplay
,但我需要从 ImageDisplay
向上发送触发器到 Home
。
本质上
Home
是带有按钮的主页。单击按钮后,ImageDisplay
就会进行异步后端调用。发生这种情况时,我希望禁用 Home
函数中的按钮,以防止用户触发正在执行的第二个 AWS Lambda 调用。我为此使用布尔值 isLoading
。一旦 axios 调用成功完成,请再次将 isLoading
设置回 false,以便可以再次启用按钮。
我一直在与自己愚蠢地斗争。我尝试了一些 Redux 选项。我现在正在进行上下文传递。我对任何明智的解决方案持开放态度。代码看起来像这样:
import {createContext} from "react";
export const MyContext = createContext(false);
function Home() {
const [isLoading, setLoading] = useState(useContext(MyContext));
return (
<div>
<Button
disabled={isLoading}
variant="contained"
onClick={() => {
setIsShow(true);
}}>
Generate with Bedrock
</Button>
<div>
<MyContext.Provider value={isLoading}>
{<ImageDisplay prompt={prompt}/>}
</MyContext.Provider>
</div>
</div>
);
}
export default Home;
export default class ImageDisplay extends React.Component<{ prompt: string }> {
state = {
isLoading: true
};
componentDidMount() {
// => load stuff
// Whilst stuff is loading, send message back up to calling function to disable button
// axios.get('URL', {
// ...
// this.setState({
// isLoading: false
// });
// }
}
render() {
return (
<>
<MyContext.Provider value={this.state.isLoading}>
<div>
{/*<HTML_STUFF goes here></HTML_STUFF>*/}
</div>
</MyContext.Provider>
</>
);
}
}
要将数据从子级传递给父级,可以将函数作为 prop 传递给子级,并从子级调用它会在函数中触发它。
function Home() {
const [isLoading, setLoading] = useState(false);
const setLoadingValue = () =>{
setLoading(false);
}
return (
<div>
<Button
disabled={isLoading}
variant="contained"
onClick={() => {
setIsShow(true);
}}>
Generate with Bedrock
</Button>
<div>
<ImageDisplay prompt={prompt} setLoadingValue={setLoadingValue}/>
</div>
</div>
);
}
export default Home;
function ImageDisplay () {
useEffect(() =>{
//make networkcall
// axios.get("https://jsonplaceholder.typicode.com/users")
// .then((res) => {
props.setLoading();
// setUsers(res.data);
// })
}, []);
return (
<>
<div>
{/*<HTML_STUFF goes here></HTML_STUFF>*/}
</div>
</>
)
}