反应状态:未捕获的TypeError:无法读取未定义的属性“值”

时间:2020-08-01 04:22:13

标签: javascript reactjs react-native

我正在跟韦斯·博斯(Wes Bos)的 React for Beginners 课程一起学习,在州视频中,他编写了以下代码:

import React, { Component } from 'react';

class AddFishForm extends Component {

    nameRef = React.createRef();
    priceRef = React.createRef();
    statusRef = React.createRef();
    descRef = React.createRef();
    imageRef = React.createRef();

    createFish = event => {
        event.preventDefault();
        const fish = {
            nameRef: this.nameRef.value.value,
            priceRef: parseFloat(this.priceRef.value.value),
            statusRef: this.statusRef.value.value, 
            descRef: this.descRef.value.value,
            imageRef: this.imageRef.value.value,
        }
        console.log(this); //or console.log(fish)
    }
    render() {
        return (
            <form className="fish-edit" onSubmit={this.createFish}>
                <input name="name" ref={this.nameRef} type="text" placeholder="Name"/>
                <input name="price" ref={this.priceRef} placeholder="Price"/>
                <select name="status" ref={this.statusRef}>
                    <option value="available">Fresh!</option>
                    <option value="unavailable">Sold Out!</option>
                </select>
                <textarea name="desc" ref={this.descRef} placeholder="Desc"/>
                <input name="image" ref={this.imageRef} type="text" placeholder="Image"/>
                <button type="submit">+ Add Fish</button>
            </form>
        )
    }
}

export default AddFishForm;

每当我尝试单击“添加鱼”按钮时,都会出现错误:

AddFishForm.js:14 Uncaught TypeError: Cannot read property 'value' of undefined
    at AddFishForm._this.createFish (AddFishForm.js:14)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:270)
    at executeDispatch (react-dom.development.js:561)
    at executeDispatchesInOrder (react-dom.development.js:583)
    at executeDispatchesAndRelease (react-dom.development.js:680)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:688)
    at forEachAccumulated (react-dom.development.js:662)
    at runEventsInBatch (react-dom.development.js:816)
    at runExtractedEventsInBatch (react-dom.development.js:824)
    at handleTopLevel (react-dom.development.js:4820)
    at batchedUpdates$1 (react-dom.development.js:18932)
    at batchedUpdates (react-dom.development.js:2150)
    at dispatchEvent (react-dom.development.js:4899)
    at interactiveUpdates$1 (react-dom.development.js:18987)
    at interactiveUpdates (react-dom.development.js:2169)
    at dispatchInteractiveEvent (react-dom.development.js:4876)

我想在他的代码中指出某些事情。他没有在其关联的绑定语句中使用构造函数(props),而是选择将createFish转换为箭头函数。我看到的关于State的几乎所有其他问题都使用构造函数。我应该效仿吗,还是可以使用箭头符号(尽管还不是标准)?


此外,他在相关的StorePicker.js文件中编写了以下代码,该代码应通过路由将您从StorePicker页面带到App页面。但是,当我单击应用程序中的“转到商店”按钮时,该应用程序只会重新加载而不会继续运行。我应该怎么做?

StorePicker.js的代码:

import React, { Fragment } from 'react';
import { getFunName } from '../helpers';

class StorePicker extends React.Component { //OR: ...extends Component (if you import { Component }).
    constructor () {
            super();
            console.log('Create a component!')
            this.goToStore = this.goToStore.bind(this);
    }
    
    myInput = React.createRef();
    goToStore(event) {
        //1. Stop the form from submitting.
            event.preventDefault();
        //2. Get the text from that input. Not going to select using document.querySelector or jQuery here.
        /*IMPORTANT!
            We need to bind ‘this’ to the StorePicker component so that it remains accessible from a member function.
            Either declare a constructor, as shown at the top, or turn goToStore into a function w/ arrow notation.
            goToStore = (event) => {}
        */
            const storeName = this.myInput.value.value;
        //3. Change the page to /store/whatever-they-entered. This uses push state instead of actually moving to a new page.
            this.props.history.push(`/store/${storeName}`);
    }

    render() {
        return (
            <Fragment>
                <h1>StorePicker</h1>
                <form className="store-selector">
                    <h2>Please enter a store.</h2>
                    <input type="text" 
                        ref={this.myInput}
                        required placeholder="Store name"
                        defaultValue={getFunName()}>
                    </input>
                    <button type="submit">Visit Store »
                    </button>
                </form>
            </Fragment>
        )
    }
}

export default StorePicker;

对于Router.js

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import StorePicker from './StorePicker';
import App from './App';
import NotFound from './NotFound';

const Router = () => (
    <BrowserRouter>
        <Switch>
            <Route exact path="/" component={StorePicker} />
            <Route path="/store/:storeId" component={App} />
            <Route component={NotFound} />  {/*Default catch-all. */}
        </Switch>
    </BrowserRouter>
);

export default Router;

1 个答案:

答案 0 :(得分:3)

问题参考

访问裁判时,您需要访问current属性。

Accessing Refs

当将引用传递到render中的元素时,对节点的引用 可以通过引用的current属性进行访问。

ref.current.<property>

代码

const fish = {
  nameRef: this.nameRef.current.value,
  priceRef: parseFloat(this.priceRef.current.value),
  statusRef: this.statusRef.current.value, 
  descRef: this.descRef.current.value,
  imageRef: this.imageRef.current.value,
}

问题1

他不使用与其关联的构造函数(props) 绑定语句,而是选择将createFish变成 箭头功能。我看到的关于State的几乎所有其他问题都使用 构造函数。我应该跟风还是可以使用 箭头符号(虽然还不是标准符号)?

AddFishForm没有状态,并且所有作为函数的类属性都是箭头函数,因此它们不需要在构造函数中明确绑定this。此外,您也可以声明状态类属性没有构造函数。

class Foo extends Component {
  state = {...}
  ...

问题2

...应该将您从StorePicker页面转到应用程序的代码 通过路由页面。但是,当我单击应用程序中的“转到商店”按钮时, 该应用程序只会重新加载,不会继续运行。我该怎么办 不一样?

这里的问题是按钮具有type="submit"且位于表单内,单击该按钮会使表单采取默认操作,即尝试提交表单并重新加载页面。 this.goToStore似乎也根本没有使用。

<form className="store-selector">
  <h2>Please enter a store.</h2>
  <input type="text" 
    ref={this.myInput}
    required
    placeholder="Store name"
    defaultValue={getFunName()}
  />
  <button type="submit"> // <-- causes form to submit and take default actions
    Visit Store »
  </button>
</form>

解决方案

  1. 将按钮类型更改为type="button"并添加一个onClick处理程序onClick={this.goToStore}
  2. this.goToStore附加到表单的onSubmit处理程序<form onSubmit={this.goToStore}>

我猜想goToStore是供表单使用的。

<form
  className="store-selector"
  onSubmit={this.goToStore}
>
  <h2>Please enter a store.</h2>
  <input type="text" 
    ref={this.myInput}
    required
    placeholder="Store name"
    defaultValue={getFunName()}
  />
  <button type="submit">
    Visit Store »
  </button>
</form>
相关问题