【发布时间】:2016-01-22 02:24:19
【问题描述】:
我想在页面加载时显示消息列表。我打电话给action 和addChangeListener 订阅componentDidMount 的更改,希望我可以从store 的服务器取回数据,虽然addChangeListener 被调用,但callback 没有被调用。似乎store 中的this.on('change', callback) 无法正常工作。有人知道我的代码有什么问题吗?我正在关注通量repo
另外,对存储中的后端数据进行 api 调用的合适位置在哪里?如果我在商店类的吸气剂中这样做可以吗?
谢谢。
组件/MessageList.js
class MessageList extends Component {
constructor(props) {
super(props)
this.renderMessage = this.renderMessage.bind(this)
this.state = {
loaded: false,
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
})
}
}
componentDidMount() {
messageActions.getAll()
messageStore.addChangeListener(this._onChange)
}
_onChange() {
console.log('on change') // <-- not being called from this point
this.setState({
dataSource: this.state.dataSource.cloneWithRows(messageStore.getAll())
})
}
//...
}
商店/MessageStore.js
let _messages = {}
function create(text, latitude, longitude) {
fetch('http://localhost:3000/api/message', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
content: text,
latitude: latitude,
longitude: longitude
})
})
.then(r => r.json())
.then(data => {
this.props.navigator.pop()
})
.done()
}
function getAllMessages(callback) {
fetch('http://localhost:3000/api/message')
.then((res) => res.json())
.then((data) => {
callback(data)
})
.done()
}
class MessageStore extends EventEmitter {
constructor() {
super()
}
emitChange() {
this.emit('change')
}
addChangeListener(callback) {
console.log('here') // <-- works
// this.on('change', callback) // <-- not working
this.on('change', () => console.log('helloooo')) // <-- not working
}
getAll() {
return _messages
}
}
dispatcher.register(action => {
switch(action.actionType) {
case 'MESSAGE_CREAT':
text = action.text.trim();
if (text !== '') {
create(text, action.latitude, action.longitude)
messageStore.emitChange()
}
break
case 'MESSAGE_ALL':
console.log('store..');
getAllMessages(data => _messages = data)
messageStore.emitChange()
}
})
const messageStore = new MessageStore()
export default messageStore
【问题讨论】:
-
你设置了dispatcher.dispatch方法来触发变化吗?
标签: reactjs ecmascript-6 react-native reactjs-flux flux