我能够在初始状态下加载,但是当我尝试提交一个新值时,我的形式中未定义:
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>
);
};
首先加载,我得到数据,然后我尝试更改城市,我只是没有定义。这是为什么呢?
我想如果我在按下按钮中设置搜索,它应该从输入字段中获取值,不是吗?
我认为您的设置是正确的。
我不认为这一行实际上返回任何内容,因为您只是在更新您的状态:
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]);
挂钩不会将搜索列为依赖项,因此它不会在每次搜索词更改时运行。
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 ]);