我这里有这么简单的代码
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [number, setNumber] = useState(0);
function chaneNumber() {
setNumber(state => state + 1);
}
console.log("here");
return (
<div className="App">
<button onClick={chaneNumber}>Change number</button>
{number}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
每次单击该按钮时,我都会在控制台中收到 2 个日志,表明该组件呈现两次。我发现一篇帖子说这是关于严格模式的,但我没有启用严格模式。为什么这个组件在每次状态更新时渲染两次?
这是一个可以尝试的代码和框链接。
假设我有一个在页面加载时调度的动作,比如说,在index.js文件中.
例
store.dispatch(loadData());
Run Code Online (Sandbox Code Playgroud)
在我的reducer中,我将状态初始化为一个对象.像这样的东西
function myReducer(state = {}, action)
Run Code Online (Sandbox Code Playgroud)
现在我有一些智能组件订阅我的状态,然后将其传递给另一个组件来显示数据.这种情况的另一个重要注意事项是数据的检索是异步发生的.我们还假设该对象的键是某个数组.所以标记组件会有这样的东西
{this.props.object.key.map(k => do something)}
Run Code Online (Sandbox Code Playgroud)
现在因为键是未定义的,我不能在它上面调用地图而且我会爆炸.我一直在处理的方式是使用简单的if检查.如果定义了key,则运行.map否则返回null.然后,当我的数据从服务器返回时,由于该组件订阅的状态发生变化,将再次调用渲染.此时,键被定义并且可以调用map.
另一种方法是定义你的状态在reducer中的样子.换句话说,如果我知道我的状态将是一个带有数组属性的对象,我可能会做这样的事情.
const initialState = {
key:[]
}
function myReducer(state = initialState, action)
Run Code Online (Sandbox Code Playgroud)
这样做将有利于现在我不需要我的if检查,因为密钥永远不会被定义.
我的问题是; 这些方法中的任何一种都比另一种更好吗?或许,还有另一种方法可以完全解决这个问题吗?
尝试使用typescript和redux构建一个简单的反应crud应用程序并运行到以下问题.我有一个具有指定签名的函数,它将一个person对象作为参数,如此处所示.
export default function savePerson(person: Person) {
return async (dispatch: any) => {
let newPerson = await axios.post('/api/people/addPeron', person);
dispatch(addPersonSuccess(person));
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我试图将我的组件连接到redux时,我遇到了麻烦mapDispatchToProps
.这是我的代码.
function mapDispatchToProps(dispatch: any) {
const actions = {
savePerson: () => dispatch(savePerson())
}
return actions;
}
Run Code Online (Sandbox Code Playgroud)
问题是savePerson函数需要一个人传递给它,但是我没有访问我的状态mapDispatchToProps
,因为函数缺少参数我的代码不会编译.有任何想法吗?
编辑解决方案:
这是代码,只需进行一次更改即可使此代码正常工作.
function mapDispatchToProps(dispatch: any) {
const actions = {
savePerson: (person: Person) => dispatch(savePerson(person))
}
return actions;
}
Run Code Online (Sandbox Code Playgroud)
我只需要将person对象传递给我正在调用的匿名函数dispatch
.
我有一个文件输入,它返回给我的文件路径,但 fileReader 给了我以下错误。
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
Run Code Online (Sandbox Code Playgroud)
我觉得我在这里错过了一些东西。我哪里错了?
import React from 'react';
export default class TestPage extends React.Component {
constructor() {
super();
this.state = {
file: ''
}
}
onChange(e) {
let reader = new FileReader();
reader.onload = function(e) {
this.setState({file: reader.result})
}
reader.readAsDataURL(e.target.value);
}
render() {
return (
<div>
<input onChange={this.onChange.bind(this)} type="file" name="file" />
<br />
<video width="400" controls>
<source src={this.state.file} type="video/mp4" />
</video>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个简单的onChange,它接受用户的输入pareses并设置要渲染的状态.这是代码.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
random: {
foo: 0
}
}
}
onChange(e) {
let random = this.state.random;
random[e.target.name] = parseFloat(e.target.value);
this.setState({random});
}
render() {
return (
<div className="App">
<input onChange={this.onChange.bind(this)} type="text" name="foo" value={this.state.random.foo} />
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我不明白的是我的小数点在哪里.我知道没有任何验证可以阻止用户输入字母,但这只是一个示例应用来测试我遇到的这个问题.当我输入小数点时,不会被渲染.我哪里错了?
function myFunction() {
var url = 'https://api.github.com/users/chaimf90/repos'
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json)
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(['Repo Name', data[0].name]);
}
Run Code Online (Sandbox Code Playgroud)
当我从脚本编辑器执行此函数时,它会按预期运行,但是当我尝试通过调用在工作表本身中调用此函数时=myFunction()
,我收到一条错误消息,指出我无权调用appendRow
.
为什么我可以从脚本编辑器而不是从工作表本身调用这个函数?
我有一个使用打字稿创建的简单反应组件,遇到以下奇怪的错误。这是我的代码。
interface State {
value: string
}
class App extends React.Component<{}, State> {
constructor() {
super();
this.state = {
value: ''
}
}
changeHandler = (e: any) => {
let state = Object.assign({}, this.state);
state.value = e.target.value;
this.setState(state);
}
render() {
return (
<div className="App">
<input
type="text"
value={this.state.value}
name="value"
onChange={this.changeHandler} />
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
这就是我得到的错误。
错误TS2540:因为它是常量或只读属性,所以无法分配给“值”。
这个错误让我想到也许这是打字稿执行不变异状态规则的方式。为了验证这一理论,我做了以下工作。
this.state.value = e.target.value
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我显然可以直接改变状态,并且可以肯定地得到相同的错误。
然后我想到了将界面更改为此的想法。
interface State {
value: Ivalue
}
interface Ivalue {
value: string;
}
Run Code Online (Sandbox Code Playgroud)
然后,我将组件重构为使用这种新接口。
class …
Run Code Online (Sandbox Code Playgroud) 我继承了一个相当大的 MVC 项目,它在它的前端使用 nodeJS,而我正在学习软件中使用的技术,我目前坚持使用它在启动时显示以下内容
Exception: Call to Node module failed with error: TypeError: Cannot read property 'publicPath' of undefined
at createWebpackDevServer (D:\PROJECT01\node_modules\aspnet-webpack\WebpackDevMiddleware.js:9:43)
Run Code Online (Sandbox Code Playgroud)
任何帮助或可能原因的一般想法将不胜感激,谢谢。
我的 React 应用程序中有一个 HOC,这里是代码。
export function checkToken<Props>(WrappedComponent: new() => React.Component<Props, {}>) {
return (
class PrivateComponent extends React.Component<Props, LocalState> {
constructor() {
super();
this.state = {
isAuthed: false
}
}
async componentDidMount() {
let token = localStorage.getItem('dash-token');
let config = {
headers: { 'x-access-token': token }
}
let response = await axios.get(`${url}/users/auth/checkToken`, config)
if (!response.data.success) {
localStorage.removeItem('dash-token');
browserHistory.push('/login');
} else {
this.setState({isAuthed: true});
}
}
render() {
let renderThis;
if (this.state.isAuthed) {
renderThis = <WrappedComponent {...this.props} />
}
return ( …
Run Code Online (Sandbox Code Playgroud) 这就是我的mapStateToProps
样子。
const mapStateToProps = (state): StateProps => {
let status = false;
if (state.productsPage.currentProduct) {
if (state.productsPage.currentProduct.status === "ACTIVE") {
status = true;
}
}
return {
showModal: state.productsPage.showModal,
currentProduct: state.productsPage.currentProduct,
isLoading: state.status.loading.PRODUCTS_EDIT,
initialValues: {
name: state.productsPage.currentProduct ? state.productsPage.currentProduct.name : "",
status,
},
};
};
Run Code Online (Sandbox Code Playgroud)
这是形状StateProps
type StateProps = {
showModal: boolean,
currentProduct: Object,
isLoading: boolean,
initialValues: {
name: string,
status: boolean,
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对连接的用法。
const connected = connect<React$StatelessFunctionalComponent<any>, StateProps>(mapStateToProps, mapDispatchToProps);
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误,我不知道这意味着什么或如何解决它。
[flow] 无法调用,因为类型为 argument 的索引器属性的键 [1] …
javascript ×8
reactjs ×8
typescript ×3
react-redux ×2
filereader ×1
flowtype ×1
node.js ×1
parsefloat ×1
redux ×1
setstate ×1
webpack ×1