首页 > 解决方案 > 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;

标签: javascriptreactjsfiltercallback

解决方案


推荐阅读