javascript - React 组件在 prop 更改时重新渲染

标签 javascript reactjs

import React from 'react';
import { render } from 'react-dom';

const x = [];

const App = props => <div style={styles}>{JSON.stringify(x)}</div>;

render(<App queries={x} />, document.getElementById('root'));

setInterval(x => x.push(Math.random()), 1000, x);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>React App</title>
</head>

<body>
  <div id="root"></div>
</body>

</html>

当我改变作为 prop 传递给它的对象时,为什么 App 组件不重新呈现。

每当我关闭并重新打开 React Dev Tools 时,它都会显示新 Prop 。 enter image description here

这里发生了什么?请帮助我理解。

谢谢!

最佳答案

本例中的答案与setState无关。当状态改变时,Sure React 会自动重新渲染(只要你没有做类似使用 PureComponent 然后改变数组或对象的事情)。但是你正在从根进行渲染,这与 react 状态无关,因为你的状态存在于 react 之外。

来自react docs on render :

If the React element was previously rendered into container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.

因此需要在根级别再次调用 render 以便 React 协调更改。最好还是创建一个新的对象/数组。所以在这种情况下,您可以执行 x = x.concat(..) 然后再次渲染。

let x = [];

const App = props => <div>{props.queries.toString()}</div>;

const renderApp = (queries) => ReactDOM.render(<App queries={queries} />, document.getElementById('root'));

setInterval(() => {
  x = x.concat(Math.random());
  renderApp(x);
}, 1000);

fiddle :https://jsfiddle.net/ferahl/p7zhs55q/1/

当然,更常见的事情是在 React 组件中使用本地 React 状态,但了解这一点是很好的,如果你不使用像 redux 这样的东西,这就是你如何将一些全局状态实现到 React 中。

关于javascript - React 组件在 prop 更改时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414281/

相关文章:

javascript - 访问容器中的Reducer返回未定义

reactjs - 如何在 JSX 中插入多行?

javascript - React,如何在 jsx 表达式中嵌入 <br/>

javascript - 未捕获的类型错误 : Cannot read property 'filter' of undefined

javascript - 基于订阅的 nosql 内存数据库

javascript - Promise.all 导致 Jest 显示 UnhandledPromiseRejectionWarning

javascript - Javascript 游戏中的对象碰撞

javascript - 在 Express 项目中使用 ES6/标签时出现语法错误/转换错误

javascript - 在 Javascript 中检查表单验证的简单按钮

javascript - jQuery .ajax 在 IE8/9 中跨域请求被拒绝访问