在调用API时,我实际上在React中遇到了一个小问题,因为ComponentWillMount
已被弃用。
我这样做了:
class MyClass extends Component {
constructor() {
super();
this.state = {
questionsAnswers: [[{ answers: [{ text: '', id: 0 }], title: '', id: 0 }]],
},
};
}
componentDidMount() {
this.getQuestions();
}
getQuestions = async () => {
let questionsAnswers = await Subscription.getQuestionsAndAnswers();
questionsAnswers = questionsAnswers.data;
this.setState({ questionsAnswers });
};
因此页面首次呈现时没有questionsAsnwers
,当我得到questionAnswers
页面被重新呈现时
有没有更好的解决方案来避免重新渲染?
答案 0 :(得分:2)
根据反应文档,处理API调用的最佳方法是在componentDidMount
方法反应lifeCycle。此时您所能做的就是添加一个微调器,使您的组件更加用户友好
希望在下一个React版本中。 React将使用suspense
方法https://medium.com/@baphemot/understanding-react-suspense-1c73b4b0b1e6
答案 1 :(得分:1)
使用带有 React.Component
的类是 componentDidMount
:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}
如果你使用带有 Hooks 的函数组件,你应该这样做:
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
示例响应:
{
"items": [
{ "id": 1, "name": "Apples", "price": "$2" },
{ "id": 2, "name": "Peaches", "price": "$5" }
]
}
来源:
答案 2 :(得分:0)
我认为,在这种情况下显示微调器是可以的。 你还应该检查ajax是否没有失败。