我正在使用React,Typescript和MobX开发简单的应用程序。用户可以使用API搜索github仓库,并以卡片形式显示结果。每个卡都可以保存到localStorage。问题是,当我单击“保存”时,在刷新页面之前,该卡在具有“已保存的存储库”的组件中不会显示相同的时间。 因此,在Card组件中,我有此方法可以更改商店中的可观察对象:
saveRepo = (e: any) => {
const { reposStore } = this.props!
e.stopPropagation()
let storage = JSON.parse(window.localStorage.getItem("repositories") || "[]")
if (!storage) {
storage = []
}
storage.push(this.props.repoItem)
window.localStorage.setItem("repositories", JSON.stringify(storage))
this.setState({
added: false
}, () => reposStore ? reposStore.refresh = !reposStore.refresh : null)
}
这是商店:
import { observable, action, decorate } from "mobx"
const APIQuery = "https://api.github.com/search/repositories?q="
export default class Repos {
repositories: any = []
refresh: boolean = false
fetchData(input: string) {
fetch(`${APIQuery}${input}`)
.then(res => res.json())
.then(data => this.repositories = data.items)
}
}
decorate(Repos, {
refresh: observable,
fetchData: action,
repositories: observable
})
const ReposStore = new Repos()
export { ReposStore }
在带有“已保存的仓库”的组件中,我尝试使用componentDidUpdate
方法接收道具,但根本没有收到道具...
SavedRepos组件:
state = {
refresh: true
}
componentDidUpdate(prevProps: any) {
const { reposStore } = this.props
if (reposStore!.refresh !== prevProps.reposStore.refresh) {
this.setState({
refresh: !this.state.refresh
})
}
}
如果我使用此方法,则只能使用一次(当我将卡保存到localStorage时,它在组件中显示的时间是相同的,但是当我保存第二项时,什么也没发生):
componentDidMount() {
const { reposStore } = this.props
if (reposStore) {
when(
() => reposStore.refresh,
() => {
this.setState({
refresh: !this.state.refresh
})
}
);
}
}
我在这里阅读了很多文档和主题,但是我找不到任何答案。更改@observable时如何重新呈现组件?