我可以访问上下文的对象,但无法更新其任何值

时间:2019-05-05 22:30:56

标签: reactjs react-context

我正在尝试使用React的上下文API管理全局状态。但是我无法弄清楚如何更新上下文,然后检索更新的上下文值。

当我console.log(this.context),但console.log(this.context.user)返回“未定义”时,我能够获取包含所有上下文的对象。

FeedContext.js

    import React, { Component } from 'react'

    const FeedContext = React.createContext({
      Feed: [],
      user: '',
      error: null,
      setError: () => {},
      clearError: () => {},
      setFeed: () => {},
      setUser: () => {}
    })

    export default FeedContext

    export class FeedProvider extends Component {
      state = {
        feed: [],
        error: null,
        user: ''
      };

      setFeed = Feed => {
        this.setState({ Feed })
      }

      setError = error => {

        console.error()
        this.setState({ error })
      }

      clearError = () => {
        console.log('context is accessed')
        this.setState({ error: null })
      }

      setUser = user => {
        console.log(user)
        this.setState({ user })
      }

      render() {
        const value = {
          feed: this.state.feed,
          error: this.state.error,
          user: this.state.user,
          setError: this.setError,
          clearError: this.clearError,
          setFeed: this.setFeed,
          setUser: this.setUser
        }

        return (
          <FeedContext.Provider value={value}>
            {this.props.children}
          </FeedContext.Provider>
        )
      }
    }

BlogFeed.js


    import React from 'react';
    import FeedContext from "../../contexts/FeedContext";
    import BlogPost from '../../Components/Container/BlogPost/BlogPost';
    import AccountPanel from '../../Components/AccountPanel/AccountPanel';
    import "./BlogFeed.css";
    import ArticleApiService from "../../services/article-api-service";
    import { Link } from "react-router-dom";

    class BlogFeed extends React.Component {

      static contextType = FeedContext;

      state = {
        feed: [],
      }

      componentDidMount() {
        this.context.clearError()
        ArticleApiService.getPosts()

此代码从上面的ArticleApiService.getPosts()获取输出, 并使用它成功更新本地状态的供稿值

      // .then((data) => {
      //   this.setState({ feed: data })
      //   return data
      // })

该代码应该从相同的输出 ArticleApiService.getPosts()使用它来更新FeedContext“提要”, 当前未更新FeedContext

          .then(this.context.setFeed)
          .catch(this.context.setError)
      }

      renderPosts() {
        const { feed = [] } = this.context

         return function(){

        }
      }
如果

feed等于this.context.feed的值, 已成功更新ablove,但尚未更新。 feed的值将被映射到 显示每个帖子的内容

       renderPosts() {
        const { feed = [] } = this.context
        return feed.map(post =>
          <BlogPost
            key={post.id}
            post={post}
          />
        )
      }

      render() {

        let feed = this.state.feed;

         const { error } = this.context

        return (
          <section className="feed-container">
            <div className="feed-grid">
              <div className="spacerLeft"></div>
              <div className="feed-grid-item">
                <h1>Blog Feed</h1>

如果以下代码的代码应显示错误  “错误”已在上下文中进行了更新,但尚未进行更新。  或者,将提要用于其他内容,我们将博客文章显示在  我们的提要,因为上面已经成功更新了本地状态,但是如果我使用this.renderPosts(),则不会显示任何内容,因为FeedContext永远不会更新。

                 {error

                  ?<p>No Posts have been created, but the good news is that 
                       you can create one 
                    <Link
                    onClick={this.handleLogoutClick}
                    to='/create_post'>
                    here
                 </Link></p>
                  // this.state.feed.length
                  // ? feed.map(post => { return <BlogPost postData={post}> 
                    </BlogPost> })
                  : ?this.renderPosts()
                    }


              </div>
              <div className="spacerRight">

                <div className="side-panels flexed">
                  {/* Future Account Panel Component */}
                  <AccountPanel className="side-panel-content"></AccountPanel>
                </div>

                <div className="side-panels flexed">
                  {/* Future Account Panel Component */}
                  <div className="side-panel-content">Categories</div>
                </div>

              </div>
            </div>
          </section>
        );
      }
    }

    export default BlogFeed;

最终,我希望能够更新Feed上下文并从中检索更新的值

1 个答案:

答案 0 :(得分:0)

  state = {
    feed: [],
    error: null,
    user: ''
  };

  setFeed = Feed => {
    this.setState({ Feed })
  }

这样,您将拥有this.state.feedthis.state.Feed-feed不等于Feed-将prop统一命名,它们区分大小写

下一步:

.then(this.context.setFeed)

它看起来不像函数调用,没有数据传递