鍍金池/ 問(wèn)答/HTML/ 如何將object類(lèi)型的redux的store數(shù)據(jù)賦值給react的state

如何將object類(lèi)型的redux的store數(shù)據(jù)賦值給react的state

剛開(kāi)始學(xué)習(xí)js,react,以及redux,在自己做練習(xí),想把store的數(shù)據(jù)傳入react的state,卻怎么也不成功,還請(qǐng)各位指導(dǎo)一下。

想做的事:
將API取得的數(shù)據(jù)(比如論壇上的帖子內(nèi)容)傳入redux保存,再傳給react組件顯示到UI上
我是這樣做的:

1.通過(guò)API取得了一些數(shù)據(jù)

{id: "111", title: "title1", body: "body1"}
{id: "222", title: "title2", body: "body2"}

2.在componentDidMount()中dispatch初始化數(shù)據(jù)用的action"iniPosts()",將數(shù)據(jù)傳入reducer處理

【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
    }
}

我的數(shù)據(jù)現(xiàn)在調(diào)整成了這樣:

reducer后的數(shù)據(jù):
[111:{id: "111", title: "title1", body: "body1"}
222:{id: "222", title: "title2", body: "body2"}]

3.現(xiàn)在我想把這個(gè)數(shù)據(jù)原樣傳給react的state
想用connect的方法傳遞數(shù)據(jù),但在mapStateToProps()中給posts賦值的結(jié)果總是空值

【APP.js】

function mapStateToProps({ ourPosts}) {

  console.log(ourPosts) // 這里可以看到reducer后的數(shù)據(jù),是和期待一樣的

  const temp = Object.keys(ourPosts).map(key => Object.assign({}, ourPosts[key]))
  temp.map((item) => ({
    [item.id]: item
  })) // 測(cè)試用
  console.log(temp) // 這里可以看到reducer后的數(shù)據(jù),是和期待一樣的

  return {
    posts: temp.map((item) => ({
      [item.id]: item
    }))
    // 這樣傳遞寫(xiě)法不對(duì)么?但是死活想不明白為什么傳不過(guò)去...
  }
}

function mapDispatchToProps(dispatch) {
  return {
    iniPosts: (data) => dispatch(iniPosts(data)), // dispatch傳入APP是成功的,可以正常調(diào)用
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

4.查看結(jié)果發(fā)現(xiàn)是空值:

【APP.js】
class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    }
  }
...
  render() {
    const { posts } = this.state
    console.log(posts) // 調(diào)用完action之后,這里是空值 []
  }
}

PS:
自己也嘗試了如下寫(xiě)法:

function mapStateToProps({ ourPosts}) {

  let a =  ourPosts;
  console.log(a) // 輸出是reducer后的數(shù)據(jù),和期待一樣
  return {
    posts: a // 在render中只能看到空值[],后來(lái)?yè)Q成 Object.assign(),但是也傳不過(guò)去
  }
}

求教在mapStateToProps()中應(yīng)該如何賦值

回答
編輯回答
貓館

使用mapStateToProps之后,就是將state映射到props上,用const { posts } = this.state不對(duì)吧,應(yīng)該是this.props。
要將值傳遞到state里面,在【APP.js】里面,this.state = {posts: []}設(shè)置state的時(shí)候,直接把從props取出來(lái)的數(shù)據(jù)賦值給狀態(tài)。

2018年1月12日 00:47