
上QQ阅读APP看书,第一时间看更新
Rendering the user interface
Now we can (re-)render our user interface every time the state changes. To keep it simple, we will not use a library yet. Perform the following steps and edit the src/index.js file, adding the following code:
First, we define a reference to the <div> root we created in the index.html file earlier:
const root = document.getElementById('root')
Then, we define a render() function, which will be subscribed to the store:
const render = () => {
In the render() function, we first clear the <div>:
root.innerHTML = ''
Next, we get all posts from the current state of the store:
const { posts } = store.getState()
Now that we have an empty container and an array of posts, we render all posts in a list:
posts.forEach((post) => {
const item = document.createElement('li')
const text = document.createTextNode(post.user + ' - ' + post.text)
item.appendChild(text)
root.appendChild(item)
})
}
Finally, we subscribe our render() function to state changes in the store:
const stopRender = store.subscribe(render)