Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - 带有axios异步的ReactJS上下文API(ReactJS context api with axios async)

I'm trying to get data from api with axios (async) in app.js and create a context to access this data in other compontents.

(我正在尝试使用app.js axios(异步)从api获取数据,并创建一个上下文以在其他组件中访问此数据。)

class App extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            result: []
        };
    }

    async componentDidMount() {
        let result = await API.getAgent();
        this.setState({
            result: result.data.success
        });
    }

  render() {
    return(
        <div className={'container-fluid'}>
            <UserProvider value={this.state.result ? this.state.result : null}>
            <Router/>
            </UserProvider>
        </div>
    )
  }
}

Well now I want to get user data in a component called info, if I use component mode it work fine:

(好吧,现在我想在名为info的组件中获取用户数据,如果我使用组件模式,则可以正常工作:)

        <UserConsumer>
            {props => {
                return <div>{props.name}</div>
            }}
        </UserConsumer>

But I want is to get it on componentDidMount

(但是我想要在componentDidMount上获取它)

static contextType = UserContext

    async componentDidMount() {
        const user = await this.context
        this.setState({
            result: user
        })
        console.log(user) // return empty
    }

But it return an empty array.

(但是它返回一个空数组。)

I can guess it because async but what is solution in this case?

(我可以猜到是因为异步,但是这种情况下的解决方案是什么?)

This is userContext.js :

(这是userContext.js :)

import React from 'react'

const UserContext = React.createContext({})

export const UserProvider = UserContext.Provider
export const UserConsumer = UserContext.Consumer
export default UserContext
  ask by tour travel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...