简体   繁体   中英

this.props in external fetch function is undefined

I am using React.js for my project. I have a problem with this.props in external fetch function. Here is my code

export default function request(method, url, body) {
  console.log(this); //undefined here
  if (method === "GET") {
    body = undefined;
  }
  return fetch(url, {
    method,
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      Authorization: "Bearer " + token
    },
    body
  }).then(res => {
    console.log(this); //undefined here
    if (res.status === 401) {
      this.props.history.push("/login");
      return Promise.reject("Unauthorized.");
    } else {
      return res;
    }
  });
}

export const get = url => request("GET", url);
export const post = (url, body) => request("POST", url, body);
export const put = (url, body) => request("PUT", url, body);
export const del = (url, body) => request("DELETE", url, body);

If res.status ===401. I hope my program can jump back to login. However, this.props in my function is always undefined. How I can bind this with specific component?

I would recommend not trying to do anything react-ish within your external request() function.

Instead, right now your request() function is returning something, therefore wherever it is called (in a react component most likely) you will be able to chain .then() onto it.

So within the react component where it is being used:

import { get } from '...'

ReactComponent extends Component {

  classMethodToMakeRequest() {
    get('someurl.com').then(() => this.props.history.push('/push/route'))
  }

}

You will only have access to this.props from within a react component.

Since the exported functions above are not components, this.props will always be unavailable. If you wanted, you could create an extra argument to accept this.props in the function and then supply this.props each time you call the functions.

Basically, you would need to write a component, that, upon being called for rendering, triggers the fetch function. As a component you could then take advantage of the withRouter function from react-router or react-router-dom . Then use:

export default withRouter(component-name)

So, any time this component is called, this.props.history becomes available, just as other props. You might as well pass any other props on the JSX tag.

Here is how it should look like:

class TryComponent extends Component {

    myFetchFunction() {
        //this.props.history is available
        //call request, get, delete... function here and pass props
    }

    render() {
        // call here or call from the constructor
        this.myFetchFunction();

        return <AnyJSX></AnyJSX>;
    }
}

export default withRouter(TryComponent);

So when you write <TryComponent foo="bar" /> , foo is available as a props and history is also available as a props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM