简体   繁体   中英

Dynamically create functions in React to be consumed for react-router-dom

I've been trying sort out how to create functions dynamically while trying to teach myself react-router-dom following the first example here https://reacttraining.com/react-router/web/guides/quick-start

I've sorted out how to create the Router & Switch stuff, but I'm at loss on how to create the supporting functions at the end of the example.

What I tried was this:

makeFunctions() {
    const { charList } = this.state;
    charList.map(char =>
        char.name.split(" ")[0] = function instance(){
            return <h2>{char.name.split(" ")[0]}</h2>;
        }    
    )
}

I'm using the Star Wars API (swapi.dev).

Take it for given that char.name.split(" ")[0], is stuff like "Luke", "Leia", Obi-wan".

What I need to produce is:

function Luke() {
    return <h2>Luke</h2>;
  }
function Leia() {
    return <h2>Leia</h2>;
  }
function Obi-wan() {
    return <h2>Obi-wan</h2>;
  }

..to complete the example I'm following. Am I close? Am I off by miles? Is this possible or simple just the wrong way to go about this? Any direction is greatly appreciated!

Thanks!!

To answer the questions popping up below. I really don't understand React or Router all that well and am kinda winging it here. The specific example I'm following from the link above is this:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>

        {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Users() {
  return <h2>Users</h2>;
}

I've dynamically rendered everything inside of App(){} from my charList fetched from swapi.dev, but I'm a loss at how to make the supporting functions at the end work as they (in the example) follow the naming of the router link & switch route statements.

Here's one way of doing it I think

window[char.name.split(" ")[0]] = function () { // your code }

and then you can simply call them by

window['Luke']();

although I'd suggest having a single function and pass the char name as param ie

let charNameHeader = function (name) {
  return `<h2>${name}</h2>`;
}

I couldn't understand your need exactly, but if you want to create some functions dynamically you can group them inside an object

 //let's say you have this array const starWarsCharacters = ["Lia", "Luke", "Whatever"]; //we can now declare an empty object const starWarsFunctions = {} //and then we create functions this way starWarsCharacters.map(el => starWarsFunctions[el] = function(){ return el}) // we can then call the function this way console.log(starWarsFunctions.Lia()) console.log(starWarsFunctions.Luke())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM