我在父组件中有一个数组,在从 api 读取一些 JSON 后需要动态更新该数组。 我正在使用 React Router,我能够将数组传递给子组件并根据数组值添加 css 类,但我似乎无法弄清楚如何正确更新我的数组并将 panelone 的数组值更改为关闭。
父组件:
import React, { Component } from 'react';
import { Route, NavLink, HashRouter } from "react-router-dom";
import Child from './components/Child';
class App extends Component {
arr = {
panelone : 'on',
paneltwo: 'off'
};
componentDidMount() {
// Some function to get JSON...
this.arr.panelone = 'off'; // ???
//...
}
render() {
return (
<div className="App">
<TopBar />
<HashRouter>
<div>
<nav>
<ul className="header">
<li><NavLink exact to="/">Overview</NavLink></li>
</ul>
</nav>
<div className="main-container">
<Route
exact path="/"
render={(props) => <Child arr = {this.arr} />}
/>
</div>
</div>
</HashRouter>
</div>
);
}
}
子组件:
import React, { Component } from 'react';
import { Link } from "react-router-dom";
class Child extends Component {
render() {
return (
<div>
//This is working OK and css class "on" is added from panelone val
<div className={'item ' + this.props.arr.panelone}>
<p>Some Title</p>
</div>
</div>
);
}
}
export default Child;
使用 React Router 时动态更新 arr 和更新子组件的正确方法是什么?
最佳答案
我将使用状态来实现这一点,然后调用 setState()
进行更新。你读过这个吗:https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class ?
您无法直接设置或更新 props。我会做这样的事情:
class App extends Component {
constructor(props) {
super(props);
this.state = {
arr = {
panelone : 'on',
paneltwo: 'off'
}
};
}
componentDidMount() {
this.setState({
arr: {
...this.state.arr,
panelone: 'off'
}
});
}
关于javascript - React 动态更新数组并将其传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227087/