我想在組件渲染之前獲取初始數據。
因此,我嘗試在componentWillMount中聲明更新操作。
雖然狀態發生變化,但確認控制檯結果在componentDidMount結果爲空時。如何在反應componentWillMount中使用數據設置?
imageUpload.js
export const IMAGE_UPLOAD = 'IMAGE_UPLOAD';
export function imageUpload(photo) {
return {
type: IMAGE_UPLOAD,
photo
}
}
Reducers.js
import { IMAGE_UPLOAD } from './actions/imageUpload';
export default function imageUpload(state = {photo: ''}, action) {
switch(action.type) {
case IMAGE_UPLOAD:
return {
...state,
photo: action.photo
}
default:
return state
}
}
App.js
import photo from './data/photo.json' // photo type: json
import imageUpload from './actions/imageUpload'
componentWillMount() {
Storage.prototype.setObject = (key, value) => {
this.setItem(key, JSON.stringify(value))
}
Storage.prototype.getObject = (key) => {
return this.getItem(key) && JSON.parse(this.getItem(key))
}
const photoData = localStorage.getObject('photos');
if(photoData) // data in localStorage
imageUpload(photoData) // state setting localStorage data
else // data not in localStorage
imageUpload(photo) // state setting photo json data
}
componentDidMount() {
console.log(this.props.photo); // result: blank (I want result: any value)
}
class App extends React.Component {
// ...
}
const mapStateToProps = (state) => ({
photo: state.imageUpload.photos
})
const mapDispatchToProps = (dispatch) =>({
imageUpload: bindActionCreators(imageUpload, dispatch)
})
export default connect(mapStateToProps, mapDispatchToProps)(App)
什麼sholud怎麼辦?
謝謝。
有在mapStateToProps打字錯誤,而不是'照片...:state.imageUpload.photos'它應該是'照片:state.imageUpload.photo' –
如果componentDidMount功能是連接組件的一部分(在您的代碼中不清楚),它的道具中沒有照片對象。你需要看看孩子的組成部分,看看它的道具。 –