编辑:
通过console.log
在异步功能之外,我可以查看数据。我也试图通过Redirect
传递这些数据。一开始我跳过了很多部分,所以下面是全部功能:
const SearchForm = () => {
const [keyword, setKeyword] = useState('')
const [fetchedData, setFetchedData] = useState([])
const [redirect, setRedirect] = useState(false)
async function fetchData() {
const { data } = await axios.post('http://127.0.0.1:8000/api/posts/search/', {keyword});
setFetchedData(data);
}
const handleSubmit = e => {
e.preventDefault();
fetchData();
setRedirect(true);
}
if (redirect) {
return <Redirect to={{ pathname: '/search', fetchedData }} />
}
return (
<div>
<form onSubmit={ handleSubmit }>
<div className='input-field'>
<input placeholder="Search whatever you wish"
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
</div>
</form>
</div>
)
}
fetchedData没有通过重定向传递。当我检查时,它只是一个空数组(这就是初始值)。
答案 0 :(得分:1)
此setFetchedData()
是异步过程。尝试与回调配合使用以获取正确的结果:
setFetchedData(data, () => {
console.log(fetchedData)
});
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script></script>
<div id="root"></div>
<script type="text/babel">
const { useState } = React
const App = () => {
const [keyword, setKeyword] = useState('Change in a sec...');
const [fetchedData, setFetchedData] = useState([]);
setTimeout(() => {
setKeyword("Hello, changed!", () => {
console.log(keyword);
});
}, 1000);
return (
<div>
{keyword}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
答案 1 :(得分:1)
在异步操作中设置状态,您可以找到更新后的状态
const SearchForm = () => {
const [keyword, setKeyword] = useState('')
const [fetchedData, setFetchedData] = useState([])
async function fetchData() {
const { data } = await axios.post('http://127.0.0.1:8000/api/posts/search/', { keyword });
setFetchedData(data);
}
console.log(fetchedData)
if (redirect) {
return <Redirect to={{ pathname: '/search', data: { fetchedData } }} />
}
return (
)
在搜索组件控制台中像这样: this.props.location.data
答案 2 :(得分:0)
要调用异步函数,应使用await
。因此,在提交处理程序中为异步部分添加IIFE。
const SearchForm = () => {
const [keyword, setKeyword] = useState('')
const [fetchedData, setFetchedData] = useState([])
const [redirect, setRedirect] = useState(false)
const handleInputChange = ({ target: { value }}) => {
setKeyword(value)
}
const handleSubmit = (e) => {
e.preventDefault()
;(async => {
const { data } = await axios.post(`http...`, { keyword })
setFetchedData(data)
})()
}
if (redirect) {
return <Redirect to={{ pathname: '/search', fetchedData }} />
}
return (
<div>
<form onSubmit={handleSubmit}>
<input onChange={handleInputChange} />
</form>
</div>
)
}
答案 3 :(得分:-1)
尝试一下,
function fetchData() {
axios.post('http://127.0.0.1:8000/api/posts/search/', {keyword}).then(data=>{
setFetchedData(data);
console.log(fetchedData)
});