【问题标题】:How to access StaticRouter's 'context' prop within a Context Provider如何在 Context Provider 中访问 StaticRouter 的“context”道具
【发布时间】:2019-07-16 03:39:39
【问题描述】:

我正在为 React 的 Context API 进行服务器端渲染实现,并且在我的 Provider 周围包裹一个 StaticRouter 时,如下所示:

<StaticRouter location={req.path} context={{users: data}}>
  <UserProvider>
    {renderRoutes(Routes)}
  </UserProvider>
</StaticRouter>

我无法从我的 Provider 组件中访问“staticContext”属性。

class UserProvider extends Component {
  constructor(props) {
    super(props)
    /* HERE */
    let users = isBrowser ? window.CONTEXT_VALUE 
    : this.props.staticContext.users;

    this.state = {
      users,
      getUsers: () => {},
      addUser: (user) => {}
    }
  }

  componentDidMount() {

  }

  render() {
    return (
      <UserContext.Provider value={this.state}>
        {this.props.children}
      </UserContext.Provider>
    );
  }
}

堆栈给了我错误:“无法读取未定义的属性'用户'”

有什么建议吗?

【问题讨论】:

    标签: reactjs server-side-rendering react-context


    【解决方案1】:

    根据docs,只有在通常的“路由”Object[] 中声明的路由才能访问staticContext 属性,而不是StaticRouter 包装的每个组件。

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 2020-06-13
      • 2020-11-06
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      相关资源
      最近更新 更多