React 状态:未捕获 TypeError:无法读取未定义的属性“value”
我正在学习 Wes Bos 的 React for Beginners 课程,在 State 视频中,他编写了以下代码:
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;
每当我尝试单击 Add Fish 按钮时,都会出现错误:
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;
问题 Refs
访问 refs 时,需要访问
current
属性。
When a ref is passed to an element in
render
, a reference to the node becomes accessible at thecurrent
attribute of the ref.
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
He does not use a constructor (props) function with its associated binding statement, and instead opts for turning createFish into an arrow function. Almost every other question on State I see uses a constructor function. Should I be following suit, or is it okay to use the arrow notation (though it is not standard yet)?
AddFishForm
没有状态,并且所有作为函数的类属性都是箭头函数,因此它们不需要在构造函数中明确将
this
绑定到它们。此外,您也可以声明没有构造函数的状态类属性。
class Foo extends Component {
state = {...}
...
问题 2
...code which is supposed to get you from the StorePicker page to the App page via routing. Yet, when I click the Go To Store button in my app, the app only reloads and does not go forth. What should I be doing differently?
这里的问题是按钮有
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>
解决方案
-
将按钮类型更改为
type="button"
并添加onClick
处理程序,onClick={this.goToStore
-
将
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>