0

Дело в том, что при нажатии кнопки у меня из инпута берется текст и через пропс передается компоненту Weather, а он уже выводит мне погоду. Но почему-то он делает это лишь один раз, либо нужно обновить приложение. Все данные доставляет, но почему-то он использует старые данные, хоть и должен новые. Как мне заставить компонент обновляться после каждого нажатия кнопки?

APP.JS

function   _onPressButton({city}) {
  if (city!=null)
  return <Weather city={city}/>
  else return <Text>Waiting..</Text>
}
const App: () => Node = () => {
  // this.state = {
  //   city:'London'
  // }
  const [text, onChangeText] = React.useState();
  const [text2, newtext] = React.useState();

  return (
    
    <SafeAreaView style={{flex:1}}>

      <TextInput
        style={styles.input}
        onChangeText={onChangeText}
        placeholder="Введите город"
        value={text}
      />
      <View>
      <Button
        title="Press me"
        onPress={() => newtext(text)}
      />
      </View>
      <View>
        <_onPressButton city={text2}/>
      </View>
     </SafeAreaView>
  );
}; 

Weather.js

import Service from "../service/fetch";

function getWeather(city){
  const [weatherList, renderWeather] = useState([]);
  useEffect(()=>{
    Service.API(city).then((json)=>{
              console.log(json);
              renderWeather([json])
              console.log(weatherList);
          });
  },[])
  console.log("УСТАНОВЛЕННЫЙ ГОРОД - "+city)
  city=null;
  return weatherList
}
const Weather=({city})=>(
   <ScrollView>{getWeather(city)?.map((val,key)=>(
   <View key={key} style={{width:'100%',marginBottom:10,flex:1,flexDirection:'row'}}>
   <Text>{val.main.temp}</Text>
   </View>
   ))}</ScrollView>
)

Weather.defaultProps={
    city:'London'
  }

1 ответ 1

0

Вы устанавливаете компонент, а далее нет тригера для повторного рендеринга.

Попробуйте вот такой вариант:

const Weather=({city})=>(
   const [weatherList, renderWeather] = useState([]);
   
   const getWheather = (city) => {
       Service.API(city).then((json)=>{
              console.log(json);
              renderWeather([json])
              console.log(weatherList);
          });
   }
   
   useEffect(()=>{
       getWheather(London);
   },[]);
   
   useEffect(()=>{
       getWheather(London);
   }, [city]);

   <ScrollView>
       {weatherList?.map((val,key)=>(
           <View key={key} style={{width:'100%',marginBottom:10,flex:1,flexDirection:'row'}}>
               <Text>{val.main.temp}</Text>
           </View>
       ))}
   </ScrollView>
)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.