我正在使用Gutenberg Editor为Wordpress创建一个块,该编辑器正在使用React js。
因此,我使用与fetch()相同的apiFetch()调用Wordpress API
class PortfolioTagsEdit extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: false,
};
}
componentDidMount() {
const { attributes } = this.props;
const { switcher } = attributes;
this.setState({ isLoading: true });
apiFetch( { path: `/wp/v2/${switcher}?post` } )
.then(data => this.setState({ data, isLoading: false }));
}
...
}对于变量switcher,我有控制器来改变这个值。
我的问题是,当我切换switcher的值时,我应该重新加载api调用,但我不知道如何重新加载)
你能帮帮我吗?
发布于 2020-07-01 23:57:20
要做到这一点,最简单的方法是在state中使用switcher变量。然后,您可以实现componentDidUpdate方法来调用apiFetch:
class PortfolioTagsEdit extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: false,
switcher: this.props.attributes.switcher
};
}
componentDidMount() {
this.callAPI()
}
componentDidUpdate(prevProps, prevState) {
if (prevState.switcher !== this.state.switcher) this.callAPI();
}
callAPI() {
const { switcher } = this.state;
this.setState({ isLoading: true });
apiFetch( { path: `/wp/v2/${switcher}?post` } )
.then(data => this.setState({ data, isLoading: false }));
}
...
}查看componentDidUpdate - https://reactjs.org/docs/react-component.html#componentdidupdate的文档
您还可以了解如何使用挂钩(特别是useEffect -https://reactjs.org/docs/hooks-reference.html#useeffect )来完成此任务
发布于 2020-07-01 23:59:58
使用react钩子,您可以使用useEffect来获取API。
function PortfolioTagsEdit({ attributes }) {
// state
const [loading, setLoading] = useState(false);
const [data, setData] = useState([])
// here useEffect will run on component mount and every-time attributes.switcher changes
useEffect(() => {
setLoading(true)
apiFetch( { path: `/wp/v2/${switcher}?post` } )
.then(data => {
setLoading(false)
setData(data)
});
}, [attributes.switcher])
return (
....
)
}https://stackoverflow.com/questions/62680567
复制相似问题