저는 React를 배우고 있으며 여전히 몇 가지를 계획하고 구현하는 방법을 알아 내려고 노력하고 있습니다. 세 가지 다른 API 호출을 수행하는 앱이 있으므로 세 가지 다른 반환 값이 있습니다. 세 가지 모두로드되었는지 여부를 알려주는 전역 상태 구성 요소를 갖고 싶습니다. 아직 적절한 방법을 찾지 못했기 때문에 여기에 내 가짜 코드가 있습니다. 그러나 이것은 현재 제 생각의 기차입니다. 주요 앱이 있습니다.
const App = () => {
return (
<div>
<GenericAPICallerA />
<GenericAPICallerB />
<GenericAPICallerC />
<div>
<APIStatus/>
</div>
</div>
);
}
이것은 모든 A, B, C API 호출이로드되었는지 여부를 반환하는 APIStatus입니다.
class APIStatus extends React.Component{
constructor(props){
super(props);
this.state = {
aLoaded: false,
bLoaded: false,
cLoaded: false,
};
}
render(){
if (this.state.aLoaded && this.state.bLoaded && this.state.cLoaded){
return <div>Everything has loaded!</div>
}
else{
return <div>Nothing has loaded!</div>
}
}
}
마지막으로 APICaller 구성 요소 중 하나입니다. 나머지는 본질적으로 동일합니다.
class GenericAPICallerA extends React.Component{
constructor(props){
super(props);
this.state = {
error: null,
isLoaded: false,
};
}
componentDidMount(){
fetch("example.com/api",{
method: 'GET',
})
.then(res => res.json())
.then(
(result) =>{
this.setState({
isLoaded: true,
});
},
(error) =>{
this.setState({
isLoaded: false,
error
});
}
)
}
render(){
const { error, isLoaded, profile } = this.state;
if (error){
return <div>Errored!</div>
} else if (!isLoaded){
// APIStatus.state.aLoaded=false
} else {
// APIStatus.state.aLoaded=true
return(
<div>Generic Caller A is done!</div>
);
}
}
}
렌더링 섹션의 주석은 어떻게해야할지 모르겠습니다. GenericAPICaller에 대한 소품으로 APIStatus를 전달해야한다고 생각하지만 GenericAPICaller 내부에서 해당 속성을 어떻게 업데이트할지 여전히 잘 모르겠습니다.
감사!
부모 구성 요소에서 함수를 만들고 자식에게 전달할 수 있습니다. 트리거되고 상태 변수가 사용될 자식에게 전달됩니다.
예를 들면 :
import React from 'react'
import ComponentA from './ComponentA'
import ComponentB from './ComponentB'
class App extends React.Component
{
constructor()
{
super()
this.state = { my_state_variable:`some value` }
}
my_function()
{
this.setState({ my_state_variable:`new value` })
}
render = () => <>
<ComponentA my_function={my_function} />
<ComponentB my_state_variable={my_state_variable} />
</>
}
export default App
화합물
import React from 'react'
const ComponentA = ({ my_function }) => <>
<button onClick={() => my_function() }>Click Me </button>
</>
export default ComponentA
ComponentB
import React from 'react'
const ComponentB = ({ my_state_variable }) => <>
<p>{my_state_variable}</p>
{my_state_variable === `some value` && <p>if some value this will render </p>}
{my_state_variable === `new value` && <p>if new value this will render </p>}
</>
export default ComponentA
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다