如何使用映射渲染 Axios 函数的结果
How to render results from Axios function with mapping
我试图在 React 中显示 axios 函数的结果。映射已在函数中定义,但我只能控制台记录第一个 'then'
中定义的结果
我已经尝试了 componentDidMount() 并且只是在渲染器中映射 return,但是我无法让它工作。我知道还有其他方法,例如将结果安装到状态并将状态映射到组件渲染中,但我试图直接从此 getReactResults() 函数获取结果。
const API_URL = 'https://api.testapi.com/?query=test';
const getReactResults = () => axios.get(API_URL)
.then((res) => res.data.items)
.then((mul) => mul.map(({name, url}) => ({
name,
url
})
)
);
class Rel extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount(){
let results = this.getReactResults();
console.log(results);
}
render(){
return(
<div>
<ul>
{results.map((item, i) => <li key={i.name}>{i.name </li>)}
</ul>
</div>
)
}
}
我收到 'result' 未定义的错误,但结果应该显示 API 的结果。
当 promise 已解决时,您可以在组件状态中设置结果,并在渲染方法中使用 this.state.results
。
const getReactResults = () =>
axios.get(API_URL).then(res =>
res.data.items.map(({ name, url }) => ({
name,
url
}))
);
class Rel extends React.Component {
state = { results: [] };
componentDidMount() {
getReactResults().then(results => {
this.setState({ results });
});
}
render() {
return (
<div>
<ul>
{this.state.results.map((item, i) => (
<li key={i}>{item.name}</li>
))}
</ul>
</div>
);
}
}
我试图在 React 中显示 axios 函数的结果。映射已在函数中定义,但我只能控制台记录第一个 'then'
中定义的结果我已经尝试了 componentDidMount() 并且只是在渲染器中映射 return,但是我无法让它工作。我知道还有其他方法,例如将结果安装到状态并将状态映射到组件渲染中,但我试图直接从此 getReactResults() 函数获取结果。
const API_URL = 'https://api.testapi.com/?query=test';
const getReactResults = () => axios.get(API_URL)
.then((res) => res.data.items)
.then((mul) => mul.map(({name, url}) => ({
name,
url
})
)
);
class Rel extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount(){
let results = this.getReactResults();
console.log(results);
}
render(){
return(
<div>
<ul>
{results.map((item, i) => <li key={i.name}>{i.name </li>)}
</ul>
</div>
)
}
}
我收到 'result' 未定义的错误,但结果应该显示 API 的结果。
当 promise 已解决时,您可以在组件状态中设置结果,并在渲染方法中使用 this.state.results
。
const getReactResults = () =>
axios.get(API_URL).then(res =>
res.data.items.map(({ name, url }) => ({
name,
url
}))
);
class Rel extends React.Component {
state = { results: [] };
componentDidMount() {
getReactResults().then(results => {
this.setState({ results });
});
}
render() {
return (
<div>
<ul>
{this.state.results.map((item, i) => (
<li key={i}>{item.name}</li>
))}
</ul>
</div>
);
}
}