저는 React-Native를 처음 사용합니다. 내 서비스에서 json 형식으로 정보를 얻고 그 후 데이터를 표시하는 화면이 있습니다. 이 화면에는 사용자가 다른 날짜를 선택할 수있는 "Calendar"구성 요소가 있습니다. 해당 구성 요소에서 예측 상태를 업데이트하는 방법을 모르겠습니다.
내 홈 화면은 다음과 같습니다.
export default function HomeScreen({ navigation }) {
const [predictions, setPredictions] = useState([]);
const [params, setParams] = useState({
lang: 'en',
date: '2020-10-11',
sport: 'soccer'
});
useEffect( () => {
loadPredictions();
}, []);
const loadPredictions = async () => {
const response = await PredictionsApi.getPredictions({params});
// console.log(response.data);
setPredictions(response.data);
}
return (
<View style={styles.main}>
<View style={styles.container}>
<Calendar />
...
</View>
</View>
}
내 캘린더 구성 요소는 다음과 같습니다.
function renderDates({props}) {
const dates = [];
for(let i=-2;i<4;++i) {
var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * i * 1000);
dates.push(
<TouchableOpacity style={styles.dates} onPress={()=> props.setPredictions({
lang: 'en',
date: '2020-02-01',
sport: 'tennis',
})
}>
<Text style={styles.selected}>{Moment(currentDate).format('ddd')}{"\n"}{Moment(currentDate).format('DD')}</Text>
</TouchableOpacity>
);
}
return dates;
}
export default function Calendar({props}) {
return (
<View style={styles.calendarContainer}>
...
<View style={styles.second}>
{renderDates({props})}
</View>
</View>
);
}
따라서이 코드에서 다르게 수행 할 것을 권장하는 몇 가지 사항이 있습니다. 그러나 질문에 답하기 위해 setPredictions
함수를 prop으로 전달한 다음 컴포넌트 props.setPredictions()
에서 호출 할 수 Calendar
있습니다.
이 아이디어의 간단한 예는 다음과 같습니다.
const Parent = () => {
const parentFunction = () => console.log('Hello from parent');
return <Child parentFunction={parentFunction} />;
};
// clicking the div in this child will call the function defined in Parent
const Child = ({parentFunction}) => <div onClick={parentFunction}>Click me</div>;
부모에서 상태를 설정하는 모든 함수에 대해 동일한 원칙을 사용할 수 있습니다.
여기서 멈추겠습니다. 이것이 귀하의 코드에 어떻게 적용되는지에 대한 질문이 있으면 문의하십시오. 나머지 코드에 대한 추가 조언이 필요하면 알려주세요. 감사.
귀하의 코드에 대한 몇 가지 우려 사항을 해결하려는 시도입니다. 귀하의 문제는 소품의 잘못된 구조화로 인해 발생했으며 실제로 하위 구성 요소의 어느 곳에서나 예측을 설정하거나 API를 호출하지 않은 것 같습니다. 나는 이것이 의미가 있기를 바랍니다.
// use const instead of function - more conventional
const HomeScreen = ({navigation}) => {
const [predictions, setPredictions] = useState([]);
const [params, setParams] = useState({
lang: 'en',
date: '2020-10-11',
sport: 'soccer',
});
useEffect(() => {
loadPredictions();
}, []);
const loadPredictions = async () => {
const response = await PredictionsApi.getPredictions({params});
// console.log(response.data);
setPredictions(response.data);
};
return (
<View style={styles.main}>
<View style={styles.container}>
{/* Pass load predictions and setParams to Calendar as props */}
<Calendar loadPredictions={loadPredictions} setParams={setParams} />
</View>
</View>
);
};
// destructuring should be used to get the individual props. If you put {props} then
// the implication is you would be using `props.props.theActualProp`
// so either remove the curly braces or destructure the actual props
// you want to use
const Calendar = props => (
<View style={styles.calendarContainer}>
<View style={styles.second}>
{/* pass all the props down to Dates component */}
{/* I also changed this to an element, since there is no reason to do otherwise */}
<Dates {...props} />
{/* I added a button here so you can actually reload the predictions */}
<TouchableOpacity onPress={props.loadPredictions}>Load new predictions</TouchableOpacity>
</View>
</View>
);
// only destructure if you are pulling individual props OUT of the `props` object
const Dates = props => {
// don't use for loops inside a function like this... it's cleaner to use the `map` method
// on an array
// cache the current time once per render if you need to
const cachedTime = new Date().getTime();
// I'm not sure why these particular numbers are important, or what you're trying to do here
// I've preserverd the behaviour from your for loop, but depending on what you're trying
// to achieve there is probably a more sensible solution to this
return [-2, -1, 0, 1, 2, 3, 4].map(val => {
const rowDate = new Date(cachedTime + 24 * 60 * 60 * val * 1000);
return (
<TouchableOpacity
// add a key when mapping over an array
key={val}
style={styles.dates}
onPress={() =>
// I changed this to setParams. I think this is what you meant, since
// setPredictions should only be form your API response?
props.setParams({
lang: 'en',
date: '2020-02-01',
sport: 'tennis',
})
}
>
<Text style={styles.selected}>
{Moment(rowDate).format('ddd')}
{'\n'}
{Moment(rowDate).format('DD')}
</Text>
</TouchableOpacity>
);
});
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다