React是否每次都会重新渲染所有组件和子组件setState?
如果是这样,为什么?我认为这个想法是React只在需要的时候渲染 - 当状态改变时.
在下面的简单示例中,两个类在单击文本时再次呈现,尽管状态在后续单击时不会更改,因为onClick处理程序始终将其state设置为相同的值:
this.setState({'test':'me'});
Run Code Online (Sandbox Code Playgroud)
我希望渲染只会在state数据发生变化时发生.
以下是该示例的代码,作为JS Fiddle和嵌入式代码段:
var TimeInChild = React.createClass({
render: function() {
var t = new Date().getTime();
return (
<p>Time in child:{t}</p>
);
}
});
var Main = React.createClass({
onTest: function() {
this.setState({'test':'me'});
},
render: function() {
var currentTime = new Date().getTime();
return (
<div onClick={this.onTest}>
<p>Time in main:{currentTime}</p>
<p>Click me to update time</p>
<TimeInChild/>
</div>
);
}
});
ReactDOM.render(<Main/>, document.body);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>Run Code Online (Sandbox Code Playgroud)
[1]: http://jsfiddle.net/fp2tncmb/2/
Run Code Online (Sandbox Code Playgroud) 当react组件状态发生变化时,将调用render方法.因此,对于任何状态更改,可以在呈现方法主体中执行操作.那么setState回调是否有特定的用例?
很好奇接近这个的正确方法是:
var Hello = React.createClass({
getInitialState: function() {
return {total: 0, input1:0, input2:0};
},
render: function() {
return (
<div>{this.state.total}<br/>
<input type="text" value={this.state.input1} onChange={this.handleChange} />
<input type="text" value={this.state.input2} onChange={this.handleChange} />
</div>
);
},
handleChange: function(e){
this.setState({ ??? : e.target.value});
t = this.state.input1 + this.state.input2;
this.setState({total: t});
}
});
React.renderComponent(<Hello />, document.getElementById('content'));
Run Code Online (Sandbox Code Playgroud)
显然你可以创建单独的handleChange函数来处理每个不同的输入,但这不是很好.类似地,您可以为单个输入创建一个组件,但我想看看是否有这样的方法.
我想问一下当我做onclick事件时为什么我的状态没有改变.我刚才搜索过我需要在构造函数中绑定onclick函数,但状态仍未更新.这是我的代码:
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import BoardAddModal from 'components/board/BoardAddModal.jsx';
import style from 'styles/boarditem.css';
class BoardAdd extends React.Component {
constructor(props){
super(props);
this.state = {
boardAddModalShow: false
}
this.openAddBoardModal = this.openAddBoardModal.bind(this);
}
openAddBoardModal(){
this.setState({ boardAddModalShow: true });
// After setting a new state it still return a false value
console.log(this.state.boardAddModalShow);
}
render() {
return (
<Col lg={3}>
<a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal}>
<div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
Create New Board
</div>
</a>
</Col> …Run Code Online (Sandbox Code Playgroud) 我正在研究todo应用程序.这是违规代码的一个非常简化的版本.我有一个复选框:
<p><input type="checkbox" name="area" checked={this.state.Pencil} onChange={this.checkPencil}/> Writing Item </p>
Run Code Online (Sandbox Code Playgroud)
这是调用复选框的函数:
checkPencil(){
this.setState({
pencil:!this.state.pencil,
});
this.props.updateItem(this.state);
}
Run Code Online (Sandbox Code Playgroud)
updateItem是一个映射到dispatch to redux的函数
function mapDispatchToProps(dispatch){
return bindActionCreators({ updateItem}, dispatch);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我调用updateItem action和console.log状态时,它总是落后一步.如果取消选中该复选框而不是true,我仍然会将true状态传递给updateItem函数.我是否需要调用另一个函数来强制状态更新?
我正在尝试学习钩子,而useState方法使我感到困惑。我正在将初始值分配给数组形式的状态。即使使用spread(...)或,useState中的set方法对我也不起作用without spread operator。我在另一台PC上制作了一个API,我正在调用它并提取要设置为状态的数据。
这是我的代码:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{
category: "",
photo: "",
description: "",
id: 0,
name: "",
rating: 0
}
];
const [movies, setMovies] = useState(initialValue);
useEffect(() => {
(async function() {
try {
//const response = await fetch(
//`http://192.168.1.164:5000/movies/display`
//);
//const json = await response.json();
//const result = json.data.result;
const result = [
{
category: …Run Code Online (Sandbox Code Playgroud) 我有调度动作的功能.我想在动作之前和之后显示一个加载器.我知道组成传递给的对象的反应setState.问题是如何以异步方式更新属性:
handleChange(input) {
this.setState({ load: true })
this.props.actions.getItemsFromThirtParty(input)
this.setState({ load: false })
}
Run Code Online (Sandbox Code Playgroud)
基本上,如果我将此属性作为应用程序状态的一部分(使用Redux),这一切都很有用,但我真的更喜欢将此属性仅用于组件状态.
我需要打开/关闭模态
$(元素).modal( '秀')
怎么做?
我handleSelection点击了一个按钮时调用的方法,但是,如果在达到状态时没有设置状态,则单击按钮this.setState({selectedFoods: newSelections});.方法中的其他所有内容都正确执行(因为我的各种console.logs告诉我:)).当第二次单击该按钮时,方法中的所有内容都会再次执行并且setState工作正常.
var Flavor = React.createClass({
getInitialState: function() {
return { foods: {}, selectedFoods: [], affinities: [] };
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({foods: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidUpdate: function () {
$('#select-food').selectize({
onChange: this.handleSelection
}
);
},
handleSelection: function (e) {
if (e.target) {
var selectedFood = e.target.id;
} else {
var selectedFood = e; …Run Code Online (Sandbox Code Playgroud) 我有一个登录页面,我用它componentWillReceiveProps来路由到下一页.但state我设置的内容componentWillReceiveProps似乎没有设定.
这是我的componentWillReceiveProps方法:
componentWillReceiveProps(nextProps) {
if (nextProps.isAuthenticated === true) {
browserHistory.push('/home');
} else {
console.log("this.props :::" + JSON.stringify(this.props))
console.log("this.state :::" + JSON.stringify(this.state))
console.log("nextProps :::" + JSON.stringify(nextProps))
this.setState({
errorMessage: nextProps.authenticationError
})
console.log("this.state :::" + JSON.stringify(this.state))
}
}
Run Code Online (Sandbox Code Playgroud)
在console output我得到是这样的:
this.props :::{"authenticationError":null}
this.state :::{"username":"35135","password":"3135","errorMessage":""}
nextProps :::{"isAuthenticated":false,"authenticationError":"Could not find user in DB."}
this.state :::{"username":"35135","password":"3135","errorMessage":""}
Run Code Online (Sandbox Code Playgroud)
即使在设置状态之后,我的状态也没有改变.
请告诉我,我做错了什么.
编辑:我有这个组件ErrorText,它接收errroMessage属性.
<ErrorText errorMsg={this.state.errorMessage}></ErrorText>
Run Code Online (Sandbox Code Playgroud) reactjs ×10
javascript ×5
setstate ×3
callback ×1
ecmascript-6 ×1
jsx ×1
react-hooks ×1
react-jsx ×1
redux ×1
state ×1