反应路由器路径:在路径内设置可选值

时间:2020-10-22 21:43:12

标签: javascript reactjs react-router react-router-v4

请考虑以下两个反应路线:

  1. /site/my/photos/:id
  2. /site/photos/:id

我希望第一个路径中的'my'是可选的。

如何将其设为可选(可能与?符号有关),然后如何检索URL中是否存在my

2 个答案:

答案 0 :(得分:1)

我认为您应该使用相同的组件定义两条路线,如下所示:


import React from 'react';
import {View, TouchableOpacity, Text} from 'react-native';
import RNFS from 'react-native-fs';

const data = {
  name: 'My name',
  age: '20',
};

const path = RNFS.DocumentDirectoryPath + '/test.json';

const App = () => {
  const handlePress = async () => {
    try {
      await RNFS.writeFile(path, data, 'utf8');
      console.log('Success!');
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <TouchableOpacity onPress={handlePress}>
        <Text>Press Me</Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

答案 1 :(得分:1)

您可以将一系列路径从react-router-dom传递到Route,例如:

<Route path={["/site/my/photos/:id", "/site/photos/:id"]} component={MyComponent} />