[英]Javascript: Passing valid parameters in function call and one turns undefined
這是一個帶有 Redux 和 Firebase 的 React web 應用程序。 當我遇到這個問題時,我已經完成了 react-redux-i18n(多語言支持)的實現。 該應用程序支持兩種語言環境,比如說“en”和“pl”。 Current locale is stored in state and in sync with firebase, that's the idea anyway and that's where I've encountered this strange behaviour: one of the 3 parameters, while present and valid before the call to the function turns undefined in the function that subsequently失敗。
這是我打電話的 function:
export const SaveLanguageToDb = (uid, user, lang) => {
console.log('in function:', uid, user)
database.ref(`users/${uid}`).update({ currentLanguage: lang, ...user })
.then(() => {
return
})
.catch(e => { console.log('Error:', e) })
}
function 采用 3 個參數:
它從兩個位置調用:
user
object 未定義,此調用失敗。這是 function 的調用組件:
import React from 'react'
import { connect } from 'react-redux'
import en from '../../../public/images/United_Kingdom.png'
import pl from '../../../public/images/Poland.png'
import { SaveLanguageToDb } from '../../actions/user'
import { setLocale, } from 'react-redux-i18n'
export const LingoFlags = ({ uid, user, SaveLanguageToDb, setLocale }) => {
console.log('before call:', uid, user)
return (
<div>
<button
className="button button--link"
onClick={() => {
setLocale('en')
SaveLanguageToDb(uid, user, 'en')
}}
>
<img src={en} alt="en" />
</button>
<button
className="button button--link"
onClick={() => {
console.log('onClick:', uid, user)
setLocale('pl')
SaveLanguageToDb(uid, user, 'pl')
}}
>
<img src={pl} alt="pl" />
</button>
</div>
)}
const matchStateToProps = (state) => ({
uid: state.auth.uid,
user: state.user,
})
const mapDispatchToProps = (dispatch) => ({
SaveLanguageToDb: (lang) => dispatch(SaveLanguageToDb(lang)),
setLocale: (lang) => dispatch(setLocale(lang))
})
export default connect(matchStateToProps, mapDispatchToProps)(LingoFlags)
console.log
確認我在調用之前有正確的數據,但在被調用的 function 中, user
object 未定義,而uid
字符串正確傳遞,如下所示:
通話前:06N6iv34gZfyWeF {displayName: "Some Name", email: "somenamel@gmail.com", emailVerified: true, numberOfVisits: 102, firstVisitAt: 1591402705798, ...} LingoFlags.js:9
onClick : 06N6iv34gZfyWeF {displayName: "Some Name", email: "somename@gmail.com", emailVerified: true, numberOfVisits: 102, firstVisit7070:2, ...} Lingo70570:28,} Lingo動作@@i18n/SET_LOCALE@19:13:40.651 redux-logger.js:1
在 function 中:06N6iv34gZfyWeF未定義user.js:41
未捕獲的錯誤:Reference.update 失敗:第一個參數包含未定義...
我希望這些信息足以讓人們對這個謎團感興趣。 謝謝你。
根據 mapDispatchToProps 'SaveLanguageToDb' 僅接收 1 個參數。 這可能是問題嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.