Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在组件中传递ID_Javascript_Reactjs_Redux_React Router - Fatal编程技术网

Javascript 在组件中传递ID

Javascript 在组件中传递ID,javascript,reactjs,redux,react-router,Javascript,Reactjs,Redux,React Router,我正在开发一款应用程序,但我目前仍在思考如何实现这一点 import React from "react" import { Switch } from "react-router-dom" import LandingPage from "./LandingPage/" import Dashboard from "./pages/Dashboard" import CustomRoute from "../utils/CustomRoute" import Pages from "./pa

我正在开发一款应用程序,但我目前仍在思考如何实现这一点

import React from "react"
import { Switch } from "react-router-dom"

import LandingPage from "./LandingPage/"
import Dashboard from "./pages/Dashboard"
import CustomRoute from "../utils/CustomRoute"
import Pages from "./pages/Pages"
import PublicTrip from "./Maps/singleTripPublic"

const Root = () => (
  <Switch>
    <CustomRoute path="/" exact component={LandingPage} />
    <CustomRoute path="/app" protectedPath component={Dashboard} />
    <CustomRoute
      path="/public/:tripId"
      render={({ match }) => <PublicTrip tripId={match.params.tripId} />}
    />
    <CustomRoute path="/" component={Pages} />
    <CustomRoute render={() => <div>404: Route not found</div>} />
    <Pages />
  </Switch>
)
export default Root

从“React”导入React
从“react router dom”导入{Switch}
从“/LandingPage/”导入LandingPage
从“/pages/Dashboard”导入仪表板
从“./utils/CustomRoute”导入CustomRoute
从“/Pages/Pages”导入页面
从“/Maps/singleTripPublic”导入PublicTrip
常量根=()=>(
}
/>
404:找不到路由}/>
)
导出默认根目录
这是我的root.js,我想知道如何将tripId传递到Link标记中,以便在单击链接时呈现public/“tripId”。如果向下滚动,可以看到带有tripId的标记。如何传入tripId,以便在单击时它实际上重定向到它。任何帮助都将不胜感激。谢谢

import React from "react"
import * as s from "./components"
import { connect } from "react-redux"
import moment from "moment"
import PropTypes from "prop-types"
import { TripPropTypes } from "../../propTypes"
import { Button } from "../../../styles/theme/styledComponents"
import { toggleWaypoint } from "../../../redux/actions/trips"
import marker from "../../icons/orange-marker.svg"
import startMarker from "../../icons/green-marker.svg"
import endMarker from "../../icons/black-marker.svg"
import { Link } from "react-router-dom"

class ActiveTripPanel extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      polylines: null,
      markers: []
    }
  }

  componentDidMount() {
    setTimeout(() => {
      this.renderWaypoints()
      this.drawPolylines()
    }, 500)
  }

  componentDidUpdate(prevProps) {
    if (prevProps.waypoints !== this.props.waypoints) {
      this.renderWaypoints()
      this.drawPolylines()
    }
  }

  drawPolylines = () => {
    if (this.state.polylines !== null) {
      this.state.polylines.active.setMap(null)
      this.state.polylines.complete.setMap(null)
      this.state.polylines.current.setMap(null)
    }

    let completeIndex = 0
    for (let i = 0; i < this.props.waypoints.length; i++) {
      if (!this.props.waypoints[i].complete) {
        completeIndex = i
        break
      }
    }

    const completed = this.props.waypoints.slice(0, completeIndex)
    const active = this.props.waypoints.slice(
      completeIndex,
      this.props.waypoints.length + 1
    )
    const current = this.props.waypoints.slice(
      completeIndex - 1,
      completeIndex + 2
    )
    const completePath = completed.map(waypoint => {
      return { lat: waypoint.lat, lng: waypoint.lon }
    })

    const activePath = active.map(waypoint => {
      return { lat: waypoint.lat, lng: waypoint.lon }
    })

    const currentPath = current.map(waypoint => {
      return { lat: waypoint.lat, lng: waypoint.lon }
    })
    const completePolyline = new window.google.maps.Polyline({
      path: completePath,
      strokeColor: "#FF0000",
      strokeOpacity: 1.0,
      strokeWeight: 2
    })

    const currentPolyline = new window.google.maps.Polyline({
      path: currentPath,
      strokeColor: "#008000",
      stokeOpacity: 1.0,
      stokeWeight: 2
    })
    const activePolyline = new window.google.maps.Polyline({
      path: activePath,
      strokeColor: "#000000",
      strokeOpacity: 1.0,
      strokeWeight: 2
    })

    completePolyline.setMap(window.map)
    activePolyline.setMap(window.map)
    currentPolyline.setMap(window.map)
    this.setState({
      polylines: {
        active: activePolyline,
        complete: completePolyline,
        current: currentPolyline
      }
    })
  }

  renderWaypoints = () => {
    let markers = []
    const baseIcon = {
      anchor: new window.google.maps.Point(15, 30),
      scaledSize: new window.google.maps.Size(30, 30),
      labelOrigin: new window.google.maps.Point(15, 13)
    }
    const icons = {
      start: {
        url: startMarker,
        ...baseIcon
      },
      end: {
        url: endMarker,
        ...baseIcon
      },
      marker: {
        url: marker,
        ...baseIcon
      }
    }
    this.props.waypoints.map((item, i) => {
      const icon =
        i === 0
          ? icons.start
          : i === this.props.waypoints.length - 1
          ? icons.end
          : icons.marker

      let center = { lat: item.lat, lng: item.lon }
      const marker = new window.google.maps.Marker({
        position: center,
        map: window.map,
        icon,
        title: item.name,
        label: {
          text: `${i + 1}`,
          color: "white",
          fontFamily: "Wals",
          fontWeight: "bold"
        }
      })
      markers.push(marker)
    })
  }

  render() {
    const publicId = ({ match })
    return (
      <s.Panel>
        {/* <s.PanelHeader>{this.props.trip.name}</s.PanelHeader>
        <s.DateLabel>
          Start: {moment(this.props.trip.start).format("YYYY-MM-DD")} - End:{" "}
          {moment(this.props.trip.end).format("YYYY-MM-DD")}
        </s.DateLabel> */}
        <Link to="/public/{match.params.tripId}">Share Trip</Link>
        <s.WaypointTracker>

          {this.props.waypoints &&
            this.props.waypoints.map(waypoint => (
              <s.WaypointStepper key={waypoint.id}>
                <div>
                  <h4>{waypoint.name}</h4>
                  <div>
                    ETA: {moment(waypoint.start).format("YYYY-MM-DD HH:mm")}
                  </div>
                  <div>
                    Status: Checked In @{" "}
                    {moment(waypoint.start).format("HH:mm")}
                  </div>
                </div>
                <div>
                  {waypoint.complete ? (
                    <Button
                      onClick={() => this.props.toggleWaypoint(waypoint.id)}
                    >
                      <i className="fa fa-check" />
                    </Button>
                  ) : (
                    <Button
                      onClick={() => this.props.toggleWaypoint(waypoint.id)}
                    >
                      <i className="fa fa-times" />
                    </Button>
                  )}
                </div>
              </s.WaypointStepper>
            ))}
        </s.WaypointTracker>
      </s.Panel>
    )
  }
}

ActiveTripPanel.propTypes = {
  trip: TripPropTypes,
  waypoints: PropTypes.array.isRequired,
  toggleWaypoint: PropTypes.func.isRequired
}

const mapStateToProps = ({ trips }) => ({
  trip: trips.activeTrip,
  waypoints: trips.activeTrip && trips.activeTrip.waypoints
})

export default connect(
  mapStateToProps,
  { toggleWaypoint }
)(ActiveTripPanel)

从“React”导入React
从“/components”以s的形式导入*
从“react redux”导入{connect}
从“时刻”导入时刻
从“道具类型”导入道具类型
从“./../propTypes”导入{TripPropTypes}
从“../../../styles/theme/styledComponents”导入{Button}
从“../../../redux/actions/trips”导入{toggleWaypoint}
从“../../icons/orange marker.svg”导入标记
从“../../icons/green marker.svg”导入startMarker
从“../../icons/black marker.svg”导入endMarker
从“反应路由器dom”导入{Link}
类ActiveTripPanel扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
多段线:空,
标记:[]
}
}
componentDidMount(){
设置超时(()=>{
此.renderwypoints()
这是drawPolylines()
}, 500)
}
componentDidUpdate(prevProps){
if(prevProps.waypoints!==此.props.waypoints){
此.renderwypoints()
这是drawPolylines()
}
}
drawPolylines=()=>{
if(this.state.polylines!==null){
this.state.polylines.active.setMap(null)
this.state.polylines.complete.setMap(null)
this.state.polylines.current.setMap(null)
}
设completeIndex=0
for(设i=0;i{
返回{lat:waypoint.lat,lng:waypoint.lon}
})
常量activePath=active.map(航路点=>{
返回{lat:waypoint.lat,lng:waypoint.lon}
})
const currentPath=current.map(航路点=>{
返回{lat:waypoint.lat,lng:waypoint.lon}
})
const completePolyline=new window.google.maps.Polyline({
路径:completePath,
strokeColor:#FF0000“,
笔划不透明度:1.0,
冲程重量:2
})
const currentPolyline=new window.google.maps.Polyline({
路径:currentPath,
strokeColor:#008000“,
不透明度:1.0,
体重:2
})
const activePolyline=new window.google.maps.Polyline({
路径:activePath,
strokeColor:#000000“,
笔划不透明度:1.0,
冲程重量:2
})
completePolyline.setMap(window.map)
activePolyline.setMap(window.map)
currentPolyline.setMap(window.map)
这是我的国家({
多段线:{
活动:活动多段线,
完成:completePolyline,
当前:当前多段线
}
})
}
渲染点=()=>{
让标记=[]
常量baseIcon={
主播:新窗口。谷歌。地图。点(15,30),
scaledSize:newwindow.google.maps.Size(30,30),
labelOrigin:newwindow.google.maps.Point(15,13)
}
常量图标={
开始:{
网址:startMarker,
…基准图标
},
完:{
url:endMarker,
…基准图标
},
标记:{
url:marker,
…基准图标
}
}
this.props.waypoints.map((项目,i)=>{
常量图标=
i==0
?图标。开始
:i==this.props.waypoints.length-1
?图标。结束
:icons.marker
让中心={lat:item.lat,lng:item.lon}
const marker=new window.google.maps.marker({
位置:中,
map:window.map,
偶像
标题:item.name,
标签:{
文本:`${i+1}`,
颜色:“白色”,
fontFamily:“Wals”,
fontWeight:“粗体”
}
})
标记器。推(标记器)
})
}
render(){
常量publicId=({match})
返回(
{/*{this.props.trip.name}
开始:{时刻(this.props.trip.Start).format(“YYYY-MM-DD”)}-结束:{'}
{矩(this.props.trip.end).format(“YYYY-MM-DD”)}
*/}
共享旅行
{this.props.waypoints&&
this.props.waypoints.map(waypoint=>(
{waypoint.name}
ETA:{时刻(航路点.start).format(“YYYY-MM-DD HH:MM”)}
状态:签入@{“}
{矩(waypoint.start).format(“HH:mm”)}
{航路点。完成了吗(
this.props.toggleWaypoint(waypoint.id)}
>
) : (
this.props.toggleWaypoint(waypoint.id)}
>
)}
))}
)
}
}
ActiveTripPanel.propTypes={
trip:TripPropType,
航路点:需要PropTypes.array.isRequired,
切换航路点:需要PropTypes.func.isRequired
}
常量mapStateToProps=({trips})=>({
tr
import React from "react"
import { connect } from "react-redux"
import { Redirect, Route } from "react-router"

import { addTokenToState } from "../redux/actions/auth"

const CustomRoute = props => {
  const { isLoggedIn, protectedPath, checkedForToken, ...rest } = props

  // If not logged in and haven't checked for token yet,
  // try to query DB for user with token:
  if (!checkedForToken && !isLoggedIn) {
    props.addTokenToState()
  }

  if (isLoggedIn || !protectedPath) {
    return <Route {...rest} />
  }

  if (protectedPath && !isLoggedIn) {
    return (
      <Redirect
        to={{
          pathname: "/login",
          state: { from: props.path }
        }}
      />
    )
  }
}

const mapStateToProps = state => ({
  isLoggedIn: state.auth.isLoggedIn,
  checkedForToken: state.auth.checkedForToken
})

const mapDispatchToProps = { addTokenToState }

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CustomRoute)

<Link to="/public/${match.params.tripId}">Share Trip</Link>
<Link to="/public/{match.params.tripId}">Share Trip</Link>
<Link to={`/public/${this.props.match.params.tripId}`}>Share Trip</Link>
<CustomRoute
   path="/public/:tripId" 
   render={({ match }) => <PublicTrip match={match} />}
   // or this render={props => <PublicTrip {...props} />}
/>
<Link to={`/public/${this.props.tripId}`}>Share Trip</Link>
<CustomRoute path="/public/:tripId" component={PublicTrip} />