I just started to learn js,react, and redux, is doing exercises by myself, but I want to transfer the data of store to the state, of react, but it is not successful. Please give me some guidance.
what you want to do:
transfer the data obtained by API (such as the content of posts on the forum) into redux for storage, and then send it to the react component to display on UI
here"s what I did:
1. Some data have been obtained through API
{id: "111", title: "title1", body: "body1"}
{id: "222", title: "title2", body: "body2"}
2. Dispatch initializes action "iniPosts ()" for data in componentDidMount (), passing data into reducer for processing
action.js
export function iniPosts(posts) {
return {
type: INI_POSTS,
posts
}
}
reducer.js
function ourPosts(state = {}, action) {
switch (action.type) {
case INI_POSTS:
const { posts } = action
let temp = [...action.posts]
return temp.map((item) => ({
[item.id] : item
}))
default:
return state
}
}
my data is now adjusted like this:
reducer:
[111:{id: "111", title: "title1", body: "body1"}
222:{id: "222", title: "title2", body: "body2"}]
3. Now I want to pass this data as is to the state of react
I want to pass the data in the method of connect, but the result of assigning a value to posts in mapStateToProps () is always null
APP.js
function mapStateToProps({ ourPosts}) {
console.log(ourPosts) // reducer
const temp = Object.keys(ourPosts).map(key => Object.assign({}, ourPosts[key]))
temp.map((item) => ({
[item.id]: item
})) //
console.log(temp) // reducer
return {
posts: temp.map((item) => ({
[item.id]: item
}))
// ...
}
}
function mapDispatchToProps(dispatch) {
return {
iniPosts: (data) => dispatch(iniPosts(data)), // dispatchAPP
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
4. Check the result and find that it is null:
APP.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
}
}
...
render() {
const { posts } = this.state
console.log(posts) // action []
}
}
PS:
himself has tried to write it as follows:
function mapStateToProps({ ourPosts}) {
let a = ourPosts;
console.log(a) // reducer
return {
posts: a // render[] Object.assign()
}
}
ask for advice on how to assign values in mapStateToProps ()