反应上下文返回未定义

时间:2018-12-14 00:15:32

标签: reactjs

我正在使用React Context api将某些状态传递给不同的子组件,并且返回未定义。

父组件

export const UserContext = React.createContext();
export class Provider extends Component {
  state = {
    editGroup: false,
  }
  render() {
    return (
      <UserContext.Provider value={{
        state: this.state
      }}>
        {this.props.children}
      </UserContext.Provider>
    )
  }
}

子组件

import { UserContext } from './index';

return (
  <React.Fragment>
    <UserContext.Consumer>
      {(context) => (
        <p>im inside the consumer {console.log(context)}</p>
      )}
    </UserContext.Consumer>
  </React.Fragment>
);

最后一个console.log返回未定义状态,我在这里做什么错了?

4 个答案:

答案 0 :(得分:3)

此外,如果覆盖上下文,请确保在构造函数中传递上下文!

    export default class Profile extends React.Component {
        static contextType = AuthContext;
        // make sure you pass the context along to super!
        constructor(props, context) {
            super(props, context);
            ...
        }
    }

答案 1 :(得分:1)

在子组件中,将使用者部分的上下文更改为值(函数参数),因为多数民众赞成是传递给提供者的道具

f.write(f'"{os.path.join(root, file)}"\n')

完整的工作样本

<UserContext.Consumer>
  {(value) => ( 
    <p>im inside the consumer {console.log(value)}</p>
  )}
</UserContext.Consumer>

输出:状态:{editGroup:false}

答案 2 :(得分:0)

我最近遇到了这个问题。就我而言,我是从提供商的外部内的门户内致电<MyContext.Consumer>{(context) => /* ... */}</MyContext.Consumer>。组成很重要!

<MyContext.Provider>
  /* ... tons and tons of code */

  <MyContext.Consumer>
    {(context) => {
      return (
        <Modal foo={context.foo} />  // gets rendered in a portal, far below the provider, but we've made a closure over it, so it's OK 
      )
    }}
  </MyContext.Consumer>
</MyContext.Provider>

答案 3 :(得分:0)

您需要在createContext()中提供上下文默认值

export const UserContext = React.createContext('default');

export const UserContext = React.createContext({ctx_key:"ctx_value"});