老师我想问一下我这里为什么获取不到topic的值

来源:4-7 话题详情页

雪挽

2018-03-27

// topic-detail/index.jsx
import React from 'react'
import { observer, inject } from 'mobx-react'
import PropTypes from 'prop-types'

@inject((stores) => {
return {
topicStore: stores.topicStore,
}
}) @observer
export default class TopicDetail extends React.Component {
componentDidMount() {
// something
}

render() {
const topic = this.props.topicStore.topics[0]
return (
<div style={{ marginTop: 100 }}>
{topic ? topic.title : 'hahah'}
</div>
)
}
}

在detai page 写了一段这样的代码 可每次渲染/detai出来都是haha。在componmentDidMount console了一下:

this.props.topicStore.topics[0]

//img.mukewang.com/szimg/5ab927590001ba4e10090073.jpg

this.props.topicStore.topics

//img.mukewang.com/szimg/5ab927ec000178e405030415.jpg

不知道为什么取不到Store里的值

列表页跟着老师走是正常的 在详情页学习之前我想简单的自己试一下 不知道这块问什么,希望老师能帮我看看。很困扰


附:

//topic-store.js
import { observable, action, extendObservable } from 'mobx'
import { topicSchema } from '../util/variable-define'
import { get } from '../util/http'

const createTopic = (topic) => {
return Object.assign({}, topicSchema, topic)
}

class Topic {
constructor(data) {
extendObservable(this, data)
}
@observable syncing = false
}

class TopicStore {
@observable topics
@observable syncing

constructor({ syncing, topics } = { syncing: false, topics: [] }) {
this.syncing = syncing
this.topics = topics.map(topic => new Topic(createTopic(topic)))
}

addTopic(topic) {
this.topics.push(new Topic(createTopic(topic)))
}

@action fetchTopic(tab) {
return new Promise((resolve, reject) => {
this.syncing = true
this.topics = []
get('/topics', {
mdrender: false,
tab,
}).then((resp) => {
if (resp.success) {
resp.data.forEach((topic) => {
this.addTopic(topic)
})
resolve()
} else {
reject()
}
this.syncing = false
}).catch((err) => {
reject(err)
this.syncing = false
})
})
}
}

export default TopicStore


写回答

1回答

Jokcy

2018-04-02

不好意思,一直没发现这个问题,mobx的数据基本就是设置和获取,我这么看你的代码看不出什么问题(而且慕课网的排版真的惨不忍睹),建议你跟踪数据设置的路径,比如你需要的数据是在什么时候设置进去的,什么时候修改的,都按照顺序打印出来跟踪变化。另外如果是一开始是没有这个key存在的数据,那么也有可能reactive的时候获取不到,建议你调试一下。

0
1
雪挽
非常感谢!
2018-04-06
共1条回复

React全栈+服务器渲染(ssr)打造社区Webapp

【毕设面试】只会写业务代码?out了,带你学会搭建属于自己的工程!

768 学习 · 414 问题

查看课程