使用方法链接未定义的未定义属性

Jen*_*Mok 1 javascript ecmascript-6 reactjs

用下面的代码我得到属性undefined的错误,我不知道是什么问题.我在它有值的渲染中执行console.log(navList).我做if(!navList)返回null我仍然得到相同的错误,我怀疑它有链接的todo.

render(){
const navList = [
            {
                path: '/boss',
                text: 'Boss',
                icon: 'boss',
                title: 'Boss List',
                component: Talent,
                hide: user.type==='boss'
            },
            {
                path: '/talent',
                text: 'Talent',
                icon: 'talent',
                title: 'Talents List',
                component: Boss,
                hide: user.type==='talent'
            }]
return(
<div>{navList.find(v=>v.path===pathname).text}</div>
)
}
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 5

array.find()返回匹配的数组元素的值,undefined如果没有找到则返回.

您的错误表明您正在尝试访问属性undefined,因此,它不能在您的阵列中找到所需的路径属性.因此.find()返回undefined然后您尝试访问undefined.text哪个导致您找到的错误.

在常规代码中,您可以执行以下操作:

let obj = navList.find(v=>v.path===pathname);
let text = obj ? obj.text : "";
Run Code Online (Sandbox Code Playgroud)

或单线方法:

(navList.find(v=>v.path===pathname) || {text: ""}).text
Run Code Online (Sandbox Code Playgroud)

就个人而言,我可能只是为此做了一点功能并称之为.

function getTextForPath(list, path) {
    let obj = list.find(v=>v.path===pathname);
    return obj ? obj.text : "";
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以使用它

return(
    <div>{getTextForPath(navList, pathname)}</div>
)
Run Code Online (Sandbox Code Playgroud)

如果您经常搜索navList路径,那么您可能需要不同类型的数据结构,例如可能Map是由路径索引的对象.然后,您可以直接通过路径请求匹配,而无需每次都进行强力搜索.