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
223 views
in Technique[技术] by (71.8m points)

javascript - (React) Dynamically display content based on state variable depending on another State variable

What I require is to display only a portion of an array of blog objects both of which (the ones I want to display and an array of all blog objects) are defined as a state variable using React hooks. This blog array is modified by form submissions and initialized by accessing a REST API endpoint (blogService is implemented using Axios).

The issue I'm facing is that while this blog array is being updated on the form submission, the array of objects that I do want to display is not.

Relevant code:

const [blogs, setBlogs] = useState([])
const [user, setUser] = useState(null)
const [currBlog, setCurrBlog] = useState(init_dict)
const [dispBlog, setDispBlog] = useState(null)

...

useEffect(() => {
    blogService.getAll().then(blogs => setBlogs(blogs))
  }, [])


useEffect(() => {
    setDispBlog(blogs.filter(b => b.user.username === user.username))
  }, [blogs, user])

const addBlog = async (event) => {
    event.preventDefault()
    let savedBlog
    try {
      savedBlog = await blogService.addBlog(currBlog)
    } catch (err) {
      console.log('err', err)
    }

    console.log('savedBlog', savedBlog)
    const newBlogs = blogs.concat(savedBlog)
    setBlogs(newBlogs)
    setCurrBlog(init_dict)
    console.log('newBlogs', newBlogs)
    console.log('dispBlog', dispBlog)
  }

return (<div> {blogs.map(blog => <p key={blog.id}>{blog.content}</p>)  // updated}
              {dispBlog.map(blog => <p key={blog.id}>{blog.content}</p) // is not updated})

The state variable array blogs is updated and dynamically rendered, but dispBlog is not.

I have tried converting dispBlog to a non-state variable, which is updated openly, but that too seems not to work.

Forgive me for not having used proper terminologies, and I realize a lot of the code is written poorly (especially mixing the use of await and then but neither of the two seem to work)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...