Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - 从道具反应传递列表到状态(React passing list to state from props)

I have two commponents.(我有两个朋友。)

Map and LfMap.(地图和LfMap。) import React, { Component } from 'react'; import { LfMap } from '../../components/Localisation/LfMap'; export class Map extends Component { constructor(props) { super(props); this.state = { dev: [], }; } componentDidMount() { fetch("URL") .then(resp => resp.json()) .then(pas => this.setState({dev: pas})); } render() { return( <React.Fragment> <LfMap list={this.state.dev}/> </React.Fragment> ); } } import React from 'react'; import { Map, CircleMarker, TileLayer, Polyline} from "react-leaflet"; import "leaflet/dist/leaflet.css"; import Control from 'react-leaflet-control'; class LfMap extends React.Component { constructor(props) { super(props); this.state = { devices: this.props.list, } } render() { return( <React.Fragment> <Map style={{ height: "480px", width: "100%" }} zoom={12} center={[22.22, 21.00]} > <TileLayer url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> </Map> </React.Fragment> ); } } export { LfMap }; And I'm passing a prop list to LfMap with list of my objects.(我正在将一个道具列表以及我的对象列表传递给LfMap。) But when I'm trying to console.log(this.state.devices) it shows Undefined but it should console my list of objets which i fetched in other component.(但是,当我尝试console.log(this.state.devices)时,它显示为Undefined,但它应该控制台我在其他组件中获取的objets列表。) Why it's happening?(为什么会这样呢?)   ask by modsell translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why set state = props ?(为什么设置状态=道具?)

is an anti-pattern , you should keep using this.prop.list in the other component.(是一个反模式 ,您应该在其他组件中继续使用this.prop.list。) Do this:(做这个:) console.log(this.props.list) it will print [], and then when the results come it will print the full array.(它将打印[],然后在结果到来时将打印整个数组。) When you need to use this array always use this.props.list.(当您需要使用此数组时,请始终使用this.props.list。) Based in your comment here is how you give solution to that: At the parent you add a function(根据您的评论,这里提供了解决方法:在父级中添加一个功能) listUpdate(newList){ this.setState({ list: newList }) } and then you pass this function to the child(然后将此功能传递给孩子) <LfMap list={this.state.dev} listUpdate={this.listUpdate}/> when you need to update it you need to call this.props.listUpdate.(需要更新时,需要调用this.props.listUpdate。) Always update the props :) that's where the reference is, this is the pattern you should follow.(始终更新props :),这是参考所在,这是您应该遵循的模式。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...