javascript - Can you call a React Context Function in a components State?
问题描述
I am trying to tackle an issue of re-setting a components state on browser reload.
The gist of it is there is a filter function in the React Context that uses the Router tool of "this.props.match.params" to obtain the desired image Id, then calls the filter function to find that image in the shared state that holds all the images. That is all well and good on initial mounting but once the browser reloads on the same route all the image data is lost. The image id from 'params' seems to remain but when it calls the filter function again it gets a undefined value.
Any ideas? I have researched for this issue with no luck. Still a fairly new coder so apologies in advance if I am overlooking something.
Using React and React Context. I have tried to use the lifecycles with no success. Also tried some very hacky function calls and/or Promise's but nothing worked.
Working lifecycle on initial mount but not on a browser reload.
export default class ImagePage extends Component {
constructor(props) {
super(props);
this.state = {
user_id: this.props.match.params.user_id,
image_id: this.props.match.params.image_id,
image:[],
redirect: false
};
}
//set context for component
static contextType = PhotoGramContext;
//set component state to selected image data
componentWillMount() {
const user = { id: this.state.user_id };
this.context.checkIfLoggedIn(user);
const getImageData = this.context.getImageData;
const image_id = this.state.image_id;
const selectedImage = new Promise((res, rej) => {
return res(getImageData(image_id));
});
this.setState({
image: selectedImage
});
}
Thought something like this to set the image data right at the start but can't call the context I guess that early.
export default class ImagePage extends Component {
constructor(props) {
super(props);
this.state = {
user_id: this.props.match.params.user_id,
image_id: this.props.match.params.image_id,
image:this.context.getImageData(this.state.image_id),
redirect: false
};
}
//set context for component
static contextType = PhotoGramContext;
解决方案
推荐阅读
- data-structures - 如何在快速联合操作中选择元素?
- reactjs - 在 react-native 中运行应用程序时出错
- dart - Dart 语言返回 void 方法
- c++ - 为什么程序不能正确计算值?
- sas - 删除 A || 的重复项 B 等于 B || 一个
- mysql - 尝试创建关系时出错:外键约束的格式不正确 - MariaDB
- r - 在闪亮的应用程序中将 plotlyOutput() 移动到服务器端
- amazon-web-services - Docker Push 添加标签而不是图像
- c# - 检查 CellPainting 行索引是否高于 0
- c++ - 如何在 Visual Studio 或 CLion 调试器中单步执行 ispc 源文件?