使用带有React Native的React Hooks获取API

时间:2019-06-12 06:29:48

标签: reactjs react-native react-hooks

我能够加载初始状态,但是当我尝试提交一个新值时,我的表单变得未定义:

const App = () => {
  const [data, setData] = useState({ list: [] });
  const [query, setQuery] = useState('Miami');
  const [search, setSearch] = useState('Miami');
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `https://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}&q=${search},us`
      );
      setData(result.data);
      console.log(search);
    };
    console.log(fetchData());

    fetchData();
  }, []);

  return (
    <ScrollView>
      <View>
        <Text>
          To get started, enter a location
        </Text>
        <View>
          <TextInput
            value={query}
            onChangeText={e => setQuery(e)}
          />
          <Button
            type='button'
            title='Fetch!'
            onPress={e => console.log(setSearch(query))}
          />
        </View>
        <View>
          {isLoading ? (
            <Text>Fetching weather...</Text>
          ) : (
            data.list.map(item => <Text key={item.dt}>{item.main.temp}</Text>)
          )}
        </View>
      </View>
    </ScrollView>
  );
};

第一次加载时,我得到了数据,然后尝试更改城市,而我却变得不确定。为什么会这样?

我认为如果我在onPress按钮中执行setSearch,它应该从输入字段中获取值,不是吗?

2 个答案:

答案 0 :(得分:1)

我认为您的设置正确。

我不认为此行实际上会返回任何内容,因为您只是在更新状态:

console.log(setSearch(query)) //this would give undefined

将按钮保留为:

      <Button
        type='button'
        title='Fetch!'
        onPress={e => (setSearch(query))}
      />

状态改变肯定是在后台发生的。您只需要更新useEffect()即可监听search状态的变化。因此,useEffect()现在将在有新城市值时执行。

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `https://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}&q=${search},us`
      );
      setData(result.data);
      console.log(search);
    };
    console.log(fetchData());

    fetchData();
  }, [search]);

答案 1 :(得分:1)

该挂钩不会将搜索列为依赖项,因此它不会在每次搜索字词更改时运行。

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `https://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}&q=${search},us`
      );
      setData(result.data);
      console.log(search);
    };
    console.log(fetchData());

    fetchData();
  }, [ search ]);