反应使用状态钩子未正确功能



编辑:

通过在异步功能之外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>
)
}

获取的数据未通过重定向传递。当我检查时,它只是一个空数组(这就是初始值(。

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>

异步操作中的设置状态 你可以像这样找到更新的状态

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

要调用异步函数,您应该使用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>
)
}

试试这个,

function fetchData() {
axios.post('http://127.0.0.1:8000/api/posts/search/', {keyword}).then(data=>{
setFetchedData(data);
console.log(fetchedData)
});

相关内容

  • 没有找到相关文章