【问题标题】:React Native TypeError: Cannot read property 'name' of undefinedReact Native TypeError:无法读取未定义的属性“名称”
【发布时间】:2021-07-23 18:27:14
【问题描述】:

我正在尝试从 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() 函数返回正确的部门 [0],但 JSX 中的部门 [0] 未定义

【问题讨论】:

    标签: javascript reactjs react-native jsx


    【解决方案1】:

    我认为在您的情况下存在一些滥用状态和数组的情况,请检查带有状态的数组的用法以及如何更新它们。

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

    【讨论】:

      【解决方案2】:

      getdepartment 在第一次渲染发生后调用。因此,在您按下“了解更多”按钮之前,department 是一个空数组

      试试这个:

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

      【讨论】:

        【解决方案3】:

        您的问题是您的 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>;
        

        一旦有数据,我还让它为每个部门显示一个&lt;Text&gt; 标签。

        第二个问题是你的数组初始化:

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

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

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

        【讨论】:

        • @coldprogrammmer 它不会出错,因为department 始终是一个数组,但是你会注意到在调用之后department 应该看起来像[dep1, dep2, ..., 123]。由于您只读取第一个值(使用[0]),它确实可以工作,但它在技术上仍然不正确。如果您曾经尝试使用数组中的所有值,您会偶然发现该错误。
        【解决方案4】:

        你应该改变

        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})))
        

        【讨论】:

          【解决方案5】:

          首先呈现 UI,此时部门为空,尝试获取名称会引发错误。您可以进行如下检查

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-05-18
            • 1970-01-01
            • 2021-12-09
            • 2019-02-17
            • 2020-11-05
            • 2020-04-17
            • 2021-11-13
            • 2022-01-14
            相关资源
            最近更新 更多