React Native TypeError: 无法读取未定义的属性"name"



我正在尝试从React Native应用程序中的URL获取部门列表

export default function App() {
var [department,setDepartment]=useState([])
const token = /* my token here */
  const getDepartments=()=>{  
    const url = /*my api's url here*/
      return fetch(url, {
          method: 'GET',
          headers: { "Authorization": "Bearer" + token ,
          'Accept': 'application/json',
          'Content-Type':'application/json'
      }
      })
          .then(response => response.json())
          .catch(error => console.error(error))
  }
   const getdepartment = async () => {
        await getDepartments().then((res) => {
        console.log('res',res)
          res.map((p, key) => {
            setDepartment([...department,department.push({
              name: p.name,
              id: p.id,
            })])
          });
        });
        console.log(department[0].name) //displays the correct value
      };

           
    
    return (
  <View>
<Button
  onPress={()=>getdepartment()}
  title="Learn More"
  color="#841584"
  accessibilityLabel="Learn more about this purple button"
/>
<Text>{department[0].name}</Text> //here lays the problem
              </View>
  )
}
尽管getdepartment()函数返回正确的department[0]

我认为在你的案例中有一些状态和数组的误用,请检查状态数组的用法以及如何更新它们。

const [theArray, setTheArray] = useState(initialArray);

setTheArray([...theArray, newElement]);

getdepartment在第一次渲染发生后调用。所以在你按下按钮之前"了解更多"department是一个空数组

试试这个:

<Text>{(department.length > 0)? department[0].name : ""}</Text>

您的问题是,您的department状态变量将是一个空数组,直到您的异步调用成功并将其替换为实际数据。

你应该显示某种加载指示器,直到数据可用:

return <View>
    <Button
        onPress= {() => getdepartment()}
        title = "Learn More"
        color = "#841584"
        accessibilityLabel = "Learn more about this purple button"
    />
    {department.length
        ? department.map(d => <Text key={d.id}>{d.name}</Text>)
        : <Text>Loading departments...</Text>}
</View>;

我还使它显示每个部门的<Text>标记,一旦它有数据。

第二个问题是你的数组初始化:
setDepartment([...department, department.push({
    name: p.name,
    id: p.id,
})])

您正在将department.push的结果添加到数组中,这是一个数字。您想要直接添加对象:

setDepartment([...department, {
    name: p.name,
    id: p.id,
}])

你应该改变

res.map((p, key) => {
  setDepartment([...department,department.push({
    name: p.name,
    id: p.id,
  })])

setDepartment(res.map((p,key)=>({name:p.name, id:p.id})))

首先呈现UI,此时部门为空,试图获取名称时会抛出错误。支票如下

{department!=null && department.length>0 && department[0].name!=null &&
 <Text>{department[0].name}</Text> 
}

相关内容

  • 没有找到相关文章

最新更新