【发布时间】:2020-11-19 21:56:43
【问题描述】:
我使用的 API 接收电话号码作为参数以从用户返回数据。所以在 UI 中,我收到了这个号码,通过console.log 我可以看到数据。但我也希望,当点击按钮时,用户会被带到一个只包含与他们相关的数据的链接,为此我相信我必须将用户重定向到一个动态链接,例如:'/user/john'。我总是在链接中收到undefined,我不知道为什么。感觉状态本身并没有存储 API 数据
const Login =()=> {
const history = useHistory()
const location = useLocation()
const [state, setState] = useState('')
const [data, setData] = useState({});
const phone = state
...
let headers = new Headers();
headers.set("Authorization", "Basic " + btoa(username + ":" + password));
const handleClick=() => {
getData();
};
const getData = async () => {
const a = await fetch(url, { method: "GET", headers: headers });
const response = await a.json();
setData(response.user[0].attributes[0]);
history.push(`/user/${data.name}`)
};
const onTextChange = event => {
setState(event.target.value);
}
<input onChange={onTextChange}>
<Button onClick={handleClick} >
login
</Button>
【问题讨论】:
标签: reactjs react-router setstate use-state