### Install Dependencies
Source: https://docs.openinula.net/docs/%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97
Run this command in the project root to install all necessary project dependencies before making changes.
```bash
npm install
```
--------------------------------
### Install OpenInula using yarn
Source: https://docs.openinula.net/
If you have yarn installed, use this command to add OpenInula to your project. Ensure yarn is installed globally first if needed.
```bash
yarn add openinula
```
--------------------------------
### Active Link Styling Example with NavLink
Source: https://docs.openinula.net/apis/Inula-router
Shows how to use NavLink for navigation, highlighting the current route with active styling. The example uses HashRouter and demonstrates setting an initial active state with isActive={true}.
```jsx
import { HashRouter, Link, Route, Switch, NavLink } from 'inula-router';
function App() {
return (
{/* 使用 NavLink 跳转到对应的路径,NavLink组件只能在Router下使用 */}
HomeAbout
Home page
} />
About Page
} />
);
}
```
--------------------------------
### Initialize OpenInula project with scaffold
Source: https://docs.openinula.net/
Execute this command in your desired directory to start a new OpenInula project using the command-line scaffold.
```bash
npx create-inula <项目名>
```
--------------------------------
### Redirect Example for Unmatched Routes
Source: https://docs.openinula.net/apis/Inula-router
This example demonstrates using the Redirect component within a Switch to handle cases where no other routes match. It redirects any unmatched URL ('*') to the home page ('/').
```jsx
import { HashRouter, Link, Route, Switch, Redirect } from 'inula-router';
function App() {
return (
{/* 使用 Link 跳转到对应的路径,Link组件只能在Router下使用 */}
Home
About
Home page
} />
About Page
} />
{/* 当URL匹配不到时,使用Redirect组件跳转到Home页面 */}
);
}
```
--------------------------------
### Example Usage of useHistory Hook
Source: https://docs.openinula.net/apis/Inula-router
This example shows how to use the `useHistory` hook to navigate to the '/home' route when a button is clicked. It demonstrates a common pattern for triggering navigation based on user interaction.
```jsx
import { useHistory } from 'inula-router';
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push('/home');
}
return (
);
}
```
--------------------------------
### Functional Component Example
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Shows a simple functional component 'Picture' and a 'Greeting' component that uses it and accepts props.
```javascript
function Picture() {
return (
);
};
const Greeting = (props) => {
return (
Hello, {props.name}!
);
};
```
--------------------------------
### Basic Navigation Example with Link and HashRouter
Source: https://docs.openinula.net/apis/Inula-router
Illustrates using the Link component within a HashRouter for client-side navigation. It shows how to create navigation links to different routes and render corresponding components.
```jsx
import { HashRouter, Link, Route, Switch } from 'inula-router';
function App() {
return (
{/* 使用 Link 跳转到对应的路径,Link组件只能在Router下使用 */}
Home
About
Home page
} />
About Page
} />
);
}
```
--------------------------------
### Basic Routing Example with Route, Link, and Switch
Source: https://docs.openinula.net/apis/Inula-router
Demonstrates setting up a basic routing structure using BrowserRouter, Link for navigation, Switch to group routes, and Route to render components based on the URL. It shows different ways to use Route with exact, render, and children props.
```jsx
import { BrowserRouter, Link, Route, Switch } from 'inula-router';
const Home = () =>
Home Page
;
const About = () =>
About Page
;
const Contact = () =>
Contact Page
;
const App = () => {
return (
Home
About
Contact
{/* 使用 Route 渲染匹配到路径的对应组件 */}
{/* 使用 exact 属性来确保只有当 URL 完全匹配时才渲染组件 */}
{/* 使用 render 属性来直接渲染一个内联函数返回的组件 */}
} />
{/* 使用 children 属性来渲染一个无论是否匹配都会显示的组件 */}
} />
);
};
```
--------------------------------
### Example Usage of Prompt Component
Source: https://docs.openinula.net/apis/Inula-router
This example demonstrates how to use the Prompt component to block navigation when a user has entered text into an input field. The `when` prop is controlled by the input's state, and the `message` prop provides a custom confirmation string.
```jsx
import { useState } from 'openinula';
import { BrowserRouter, Link, Switch, Route, Prompt } from 'inula-router';
function PromptDemo() {
return (
Form
Other Page
} />
Other Page} />
);
}
function InputForm() {
let [isBlocking, setIsBlocking] = useState(false);
return (
);
}
```
--------------------------------
### Create a basic OpenInula component
Source: https://docs.openinula.net/
This example demonstrates how to import OpenInula, define a simple 'HelloWorld' functional component, and render it to the DOM. It requires Babel compilation for JSX.
```jsx
import { render } from 'openinula';
const HelloWorld = () => {
return (
Hello, World!
);
};
render(
,
document.getElementById('root')
);
```
--------------------------------
### JSX Fragment Example
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Demonstrates the use of JSX fragments to return multiple top-level elements. Use <>...> or ....
```jsx
<>
Hello, {props.name}!
;
>
```
--------------------------------
### Example Usage of useParams Hook
Source: https://docs.openinula.net/apis/Inula-router
This example shows how to use the `useParams` hook to extract a `userid` parameter from the URL (e.g., '/user/:userid'). The extracted parameter is then displayed on the page.
```jsx
import { HashRouter, Switch, Route, useParams } from 'inula-router';
const User = () => {
// 使用 useParams 获取URL中对应的参数
const { userid } = useParams();
return
{userid} profile page
;
};
function App() {
return (
}/>
);
}
```
--------------------------------
### Asynchronous Action Example
Source: https://docs.openinula.net/apis/Inula-X
Demonstrates an asynchronous action using the `async` keyword. This action handles asynchronous operations, such as API calls, and can also invoke other actions within the store using `this`.
```javascript
const getStore = createStore({
id: 'user',
state: {
visible: true
},
actions: {
async update(state, payload) {
// 更新user信息是异步方法,action为异步action
const data = await updateUser(payload);
if (data.success) {
// 可以通过this调用该store其他的action
this.hideModal();
}
},
hideModal(state) {
state.visible = false;
},
},
});
```
--------------------------------
### Synchronous Action Example
Source: https://docs.openinula.net/apis/Inula-X
Illustrates a synchronous action within a store. This action performs a synchronous update and can call other actions within the same store using `this`.
```javascript
const getStore = createStore({
id: 'user',
state: {
visible: true
},
actions: {
update(state, payload) {
// 更新user信息是同步方法,action为同步action
const data = updateUsersync(payload);
if (data.success) {
// 可以通过this调用该store其他的action
this.hideModal();
}
},
hideModal(state) {
state.visible = false;
},
},
});
```
--------------------------------
### Component Design Example
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Illustrates the design of reusable components like Button, Form, and Page, adhering to principles of single responsibility and open/closed.
```javascript
import Inula, { render, Component } from 'openinula';
// 示例组件 - 按钮组件
class Button extends Component {
render() {
const { text, onClick } = this.props;
return (
);
}
}
// 示例组件 - 表单组件
class Form extends Component {
handleSubmit = (event) => {
event.preventDefault();
// 处理表单提交逻辑
}
render() {
return (
);
};
}
// 示例组件 - 页面组件
class Page extends Component {
render() {
return (
示例页面
);
};
}
// 渲染页面
render(, document.getElementById('root'));
```
--------------------------------
### Install OpenInula using npm
Source: https://docs.openinula.net/
Use this command to add the latest version of the OpenInula package to your project via npm. You can also specify a particular version.
```bash
npm install openinula
```
--------------------------------
### Example Usage of useLocation Hook
Source: https://docs.openinula.net/apis/Inula-router
This example demonstrates how to use the `useLocation` hook within a component to log the current location object whenever it changes. It utilizes `useEffect` to react to location updates.
```jsx
import { useLocation } from 'inula-router';
function App() {
{/* 使用useLocation获取当前位置 */}
let location = useLocation();
useEffect(() => {
console.log('location change to ', location);
}, [location]);
}
```
--------------------------------
### Clone Remote Repository
Source: https://docs.openinula.net/docs/%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97
Clone the remote openInula repository to your local machine to start contributing.
```bash
git clone {$remote_link}
```
--------------------------------
### ir.head(url[, config])
Source: https://docs.openinula.net/apis/Inula-request
Sends a HEAD network request to the specified URL. This request is similar to GET but only returns the response headers, not the body.
```APIDOC
## ir.head(url[, config])
### Description
Sends a HEAD network request to the specified URL. This request is similar to GET but only returns the response headers, not the body. It returns a Promise object.
### Method
HEAD
### Endpoint
[url]
### Parameters
#### Path Parameters
- **url** (string) - Required - The URL to send the HEAD request to.
- **config** (IrRequestConfig) - Optional - Configuration object for the request, including headers.
### Request Example
```javascript
// Using default configuration to send a HEAD request
ir.head('https://api.example.com/data')
.then(response => {
// Request successful, process response headers
})
.catch(error => {
// Request failed, handle error
});
// Using custom configuration to send a HEAD request
ir.head('https://api.example.com/data', {
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Authorization': 'your-token'
}
})
.then(response => {
// Process response headers
})
.catch(error => {
// Request failed, handle error
});
```
### Response
#### Success Response (200)
- **IrResponse** - The response from the server, containing headers and metadata.
#### Response Example
(Response structure depends on the server's implementation, primarily headers)
```
--------------------------------
### Share State with useContext
Source: https://docs.openinula.net/apis/Inula
Utilize useContext to share state across components without manual prop drilling. This example demonstrates creating a context, providing a value, and consuming it in a child component.
```javascript
import Inula, { createContext, useContext, useState, render } from 'openinula';
// 创建一个上下文对象
const Context = createContext();
// 组件A:向上下文中提供一个共享的数据
const ComponentA = () => {
const [count, setCount] = useState(0);
return (
);
}
// 组件B:从上下文中获取共享的数据
const ComponentB = () => {
const count = useContext(Context);
return
当前计数:{count}
;
}
// 主组件
const App = () => {
return ;
}
render(
,
document.getElementById('root')
);
```
--------------------------------
### Register Request Interceptor
Source: https://docs.openinula.net/apis/Inula-request
Implement request interceptors to modify requests before they are sent. This example shows how to add an Authorization header, handle errors, and conditionally apply the interceptor using `runWhen`.
```javascript
// 定义一个成功回调函数
const fulfilledCallback = (config) => {
// 修改请求配置或添加通用参数
config.headers.Authorization = 'new token';
return config;
};
// 定义一个拒绝回调函数
const rejectedCallback = (error) => {
console.error('请求失败!', error);
return Promise.reject(error);
};
// 定义拦截器选项
const options = {
synchronous: true, // 选择同步执行拦截器,默认为异步执行
runWhen: (config) => config.method === 'GET', // 只在请求方法为GET时运行拦截器
};
// 注册拦截器
const interceptorId = ir.interceptors.request.use(
fulfilledCallback,
rejectedCallback,
options,
);
// 发起请求
ir.get('https://www.example.com')
.then((response) => {
console.log('响应数据:', response.data);
})
.catch((error) => {
console.error('请求出错!', error);
});
// 取消拦截器
ir.interceptors.request.eject(interceptorId);
```
--------------------------------
### Scaffold project template selection
Source: https://docs.openinula.net/
During project creation, you will be prompted to select a template. 'Simple-app' is available and comes with OpenInula pre-installed.
```bash
Need to install the following packages:create-inula@0.0.2
Ok to proceed? (y) y
? Please select the template (Use arrow keys)
> Simple-app
```
--------------------------------
### Get DOM Node for Class Component - Inula
Source: https://docs.openinula.net/apis/Inula
Use findDOMNode to get the browser DOM node for a class component instance. This is typically used within lifecycle methods like componentDidMount.
```javascript
import { Component, findDOMNode, render } from 'openinula';
class App extends Component {
componentDidMount() {
const input = findDOMNode(this);
input.select()
}
render() {
return
}
}
render(, document.getElementById('root'));
```
--------------------------------
### Create Intl Instance with Configuration
Source: https://docs.openinula.net/apis/Inula-intl
Use createIntl to initialize an internationalization instance with locale and message configurations. This method requires careful timing due to rendering dependencies.
```javascript
import { createIntl, createIntlCache, IntlProvider } from 'inula-intl';
const cache = createIntlCache();
const props = {
locale: 'en',
messages: {
greeting: 'hello, world',
},
};
const Component = (props) => {
// 受渲染时机影响,createIntl方式需控制时序,否则慢一拍
const intl = createIntl({ ...props }, cache);
const msg = intl.formatMessage({ id: 'greeting' });
return (
createIntl-Demo
{msg}
);
};
```
--------------------------------
### Create Local Working Directory
Source: https://docs.openinula.net/docs/%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97
Use this command to create a new directory for your local development work.
```bash
mkdir ${your_working_dir}
cd ${your_working_dir}
```
--------------------------------
### ir.create([config])
Source: https://docs.openinula.net/apis/Inula-request
Creates an independent ir instance. This allows for custom configurations such as baseURL, timeout, and headers for specific sets of requests.
```APIDOC
## ir.create([config])
### Description
Creates an independent ir instance. This allows for custom configurations such as baseURL, timeout, and headers for specific sets of requests.
### Method Signature
```typescript
ir.create(config?: IrRequestConfig): IrInstance;
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// Create an independent ir instance
const instance = ir.create({
baseURL: 'https://www.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'your-token'
}
});
// Send requests using the independent instance
instance.get('/data')
.then(response => {
// Request successful, process response data
})
.catch(error => {
// Request failed, handle error
});
```
### Response
#### Success Response (200)
Returns an `IrInstance` object.
#### Response Example
```json
{
"example": "IrInstance object"
}
```
```
--------------------------------
### Create a Custom Request Instance with ir.create
Source: https://docs.openinula.net/apis/Inula-request
Use ir.create to instantiate a new ir request instance with custom configurations like baseURL, timeout, and headers. This allows for isolated request settings.
```javascript
const instance = ir.create({
baseURL: 'https://www.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'your-token'
}
});
instance.get('/data')
.then(response => {
})
.catch(error => {
});
```
--------------------------------
### Check if an element is a Context Consumer
Source: https://docs.openinula.net/apis/Inula
Use `isContextConsumer` to determine if an element is a Context component. Import `isContextConsumer` from 'openinula'. Note: The example incorrectly uses `isContextProvider` for the consumer check.
```javascript
import Inula, { createContext, isContextProvider } from 'openinula';
const MyContext = createContext();
console.log(isContextProvider(MyContext.Consumer)); // 输出: true
console.log(isContextProvider(() => {})); // 输出: false
```
--------------------------------
### createIntl()
Source: https://docs.openinula.net/apis/Inula-intl
Creates an internationalization (i18n) instance to access relevant i18n functionalities. It takes a configuration object and an optional cache object.
```APIDOC
## createIntl()
### Description
Creates an internationalization (i18n) instance to access relevant i18n functionalities.
### Function Signature
```typescript
function createIntl(config: ConfigProps, cache?: I18nCache);
```
### Parameters
#### config (ConfigProps) - Required
Configuration object for internationalization. It includes:
- `locale` (Locale): The current locale.
- `messages` (AllMessages): All available messages for different locales.
- `defaultLocale` (string): The default locale to fall back to.
- `RenderOnLocaleChange` (boolean): Whether to re-render on locale change.
- `children` (any): Children elements.
- `cache` (I18nCache): Optional cache object.
#### cache (I18nCache) - Optional
An optional cache object created by `createIntlCache` to optimize application performance.
### Example
```javascript
import { createIntl, createIntlCache, IntlProvider } from 'inula-intl';
const cache = createIntlCache();
const props = {
locale: 'en',
messages: {
greeting: 'hello, world',
},
};
const Component = (props) => {
const intl = createIntl({ ...props }, cache);
const msg = intl.formatMessage({ id: 'greeting' });
return (
createIntl-Demo
{msg}
);
};
```
```
--------------------------------
### Run Tests
Source: https://docs.openinula.net/docs/%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97
Execute all project tests to ensure your changes do not introduce regressions. This is a required step before submitting a pull request.
```bash
npm run test
```
--------------------------------
### Ref for Direct DOM Manipulation
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Shows how to use useRef to get a direct reference to a DOM element. This allows for imperative actions like accessing input values or managing focus.
```javascript
import { useRef } from "openinula";
function Component() {
const inputRef = useRef(null);
const handleClick = () => {
alert(`Input value: ${inputRef.current.value}`);
};
return (
);
}
```
--------------------------------
### Rendering a Component
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Demonstrates how to render a component ('Counter') into a specific DOM element ('root') using the 'render' function.
```javascript
import { render } from 'openinula';
import { Counter } from './Counter.js'
function App() {
render(
,
document.getElementById('root')
);
};
```
--------------------------------
### Access DOM Elements with useRef
Source: https://docs.openinula.net/apis/Inula
Use useRef to get direct access to DOM elements within a component. The ref's current property holds the element, allowing you to imperatively interact with it, like setting focus.
```javascript
import Inula, { useRef, render } from 'openinula';
function RefDemo() {
const inputRef = useRef(null);
const handleButtonClick = () => {
// 使用 ref 获取 input 元素的引用,并设置焦点
inputRef.current.focus();
};
return (
);
}
render(
,
document.getElementById('root')
);
```
--------------------------------
### ir.options(url[, config])
Source: https://docs.openinula.net/apis/Inula-request
Sends an OPTIONS network request to the specified URL to retrieve information about the communication options for the target resource. It returns a Promise object.
```APIDOC
## ir.options(url[, config])
### Description
Sends an OPTIONS network request to the specified URL to retrieve information about the communication options for the target resource, such as supported request methods and headers. It returns a Promise object.
### Method
OPTIONS
### Endpoint
[url]
### Parameters
#### Path Parameters
- **url** (string) - Required - The URL of the target resource.
- **config** (IrRequestConfig) - Optional - Configuration object for the request, including headers.
### Request Example
```javascript
// Using default configuration to send an OPTIONS request
ir.options('https://www.example.com/data')
.then(response => {
// Request successful, process response
})
.catch(error => {
// Request failed, handle error
});
// Using custom configuration to send an OPTIONS request
ir.options('https://api.example.com/data', {
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Authorization': 'your-token'
}
})
.then(response => {
// Request successful, process response
})
.catch(error => {
// Request failed, handle error
});
```
### Response
#### Success Response (200)
- **IrResponse** - The response from the server, containing communication options.
#### Response Example
(Response structure depends on the server's implementation)
```
--------------------------------
### RawIntlProvider with createIntl
Source: https://docs.openinula.net/apis/Inula-intl
RawIntlProvider offers the same internationalization context as IntlProvider but requires an explicit i18n object, typically created using createIntl. This is a lower-level component.
```typescript
import { RawIntlProvider, createIntl } from 'inula-intl';
const locale = 'en';
const messages = {
'greeting': 'hello,world!'
};
const intl = createIntl({
locale: locale,
messages: messages
},
cache
);
function App() {
return (
{children}
);
};
```
--------------------------------
### Modifying State Using Actions in a React Component
Source: https://docs.openinula.net/apis/Inula-X
Shows how to trigger actions to modify state within a React component. Actions can be called directly or via the $a property. This example includes actions for incrementing a value and adding a specific amount.
```javascript
const getStore = createStore(
{
id: 'value',
state: {
val: 0,
},
actions: {
plusOne(state) {
state.val += 1;
},
plusValue(state, value) {
state.val += value;
},
},
},
);
function App() {
const store = getStore();
return (
<>
{store.val}
{/* 修改state值 */}
>
);
}
```
--------------------------------
### Handle Download Progress with onDownloadProgress
Source: https://docs.openinula.net/apis/Inula-request
Use the `onDownloadProgress` callback to monitor download progress. This function receives progress events and can be used to update UI elements like progress bars.
```javascript
ir.get('https://www.example.com/download', {
onDownloadProgress: function(progressEvent) {
// 计算下载进度的百分比
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
// 更新用户界面上的进度条等元素
console.log('下载进度:' + percentCompleted + '%');
}
})
```
--------------------------------
### Class Component Lifecycle Methods
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Demonstrates the core lifecycle methods for class components: constructor, componentDidMount, componentDidUpdate, and componentWillUnmount. Use these to manage component state and side effects.
```javascript
import { Component } from 'openinula';
class Counter extends Inula.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
console.log('Constructor');
}
componentDidMount() {
console.log('Component Did Mount');
}
componentDidUpdate() {
console.log('Component Did Update');
}
componentWillUnmount() {
console.log('Component Will Unmount');
}
handleIncrement = () => {
this.setState(prevState => ({
counter: prevState.counter + 1
}));
};
render() {
console.log('Render');
return (
Counter: {this.state.counter}
);
}
}
```
--------------------------------
### onDownloadProgress
Source: https://docs.openinula.net/apis/Inula-request
Sets a callback function to handle download progress events. This allows for UI updates like progress bars during file downloads.
```APIDOC
## onDownloadProgress
### Description
Sets a callback function to handle download progress events. This allows for UI updates like progress bars during file downloads.
### Parameters
#### Request Body
- **onDownloadProgress** (function) - Optional - A callback function that receives progress events.
### Request Example
```javascript
ir.get('https://www.example.com/download', {
onDownloadProgress: function(progressEvent) {
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log('下载进度:' + percentCompleted + '%');
}
})
```
```
--------------------------------
### RawIntlProvider
Source: https://docs.openinula.net/apis/Inula-intl
The RawIntlProvider component also provides the internationalization context. Unlike IntlProvider, it does not process the i18n object internally and requires the developer to pass an i18n object, often created with createIntl.
```APIDOC
## RawIntlProvider
### Description
Provides the internationalization (i18n) context. Requires an explicit `i18n` object to be passed.
### Props
- **value** (I18n) - Required - An `I18n` object containing internationalization configuration and translation information.
- **children** (any) - Optional - Child components to be wrapped.
### Example
```javascript
import { RawIntlProvider, createIntl } from 'inula-intl';
const locale = 'en';
const messages = {
'greeting': 'hello,world!'
};
const intl = createIntl({
locale: locale,
messages: messages
}, cache);
function App({ children }) {
return (
{children}
);
}
```
**Note**: `RawIntlProvider` is a lower-level component and is less commonly used directly. It's generally recommended to use higher-level components like `IntlProvider`.
```
--------------------------------
### Create a Custom Fetch Hook
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Create a custom hook 'useFetch' to encapsulate data fetching logic. This hook manages 'data' and 'loading' states and can be reused across components.
```javascript
import Inula, { useState, useEffect } from 'openinula';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const data = await response.json();
setData(data);
setLoading(false);
}
fetchData();
}, [url]);
return { data, loading };
}
```
--------------------------------
### Create a Store Object with State, Actions, and Computed Properties
Source: https://docs.openinula.net/apis/Inula-X
Defines a Store object using createState, including its ID, initial state, actions for modifying state, and computed properties for derived state. Ensure state, actions, and computed properties do not have name collisions.
```javascript
const store = createState({
// id 用于标识一个Store对象
id: 'user',
// state 用于存放数据
state: {
data: {
list: [
{ id: 1, name: 'liming', age: 18 },
{ id: 2, name: 'xiaohong', age: 20 },
],
},
loading: false,
selectUsers: [1],
},
// action 用于修改state中的数据
actions: {
addUser(state, payload) {
state.data.list.push(payload);
},
addSelectedUser(state, payload) {
state.selectUsers.push(payload);
},
setLoading(state) {
state.loading = true;
},
},
// computed 用于获取state状态变量的计算属性
computed: {
users: state => state.data.list,
userCount(states) {
// 通过this获取其他computed的值
return this.users.length;
},
},
});
```
--------------------------------
### Scaffold project build type selection
Source: https://docs.openinula.net/
You can choose between webpack or vite as your build type when using the scaffold. Refer to their respective documentation for guidance.
```bash
? Please select the build type (Use arrow keys)
> webpack
vite
```
--------------------------------
### Create Intl Cache Instance
Source: https://docs.openinula.net/apis/Inula-intl
Create an Intl cache instance using createIntlCache for optimizing application performance. This cache is typically passed as the second argument to createIntl.
```javascript
const cache = createIntlCache();
const intl = createIntl(config, cache);
```
--------------------------------
### createContext
Source: https://docs.openinula.net/apis/Inula
`createContext` creates a context object that can be accessed by different components, eliminating the need for prop drilling.
```APIDOC
## createContext
### Description
Creates a context object for sharing data across components without explicit prop passing.
### Interface Definition
```typescript
function createContext(val: T): ContextType
```
- `val`: The initial value of the context.
### Example
```javascript
import { createContext, render, useContext } from 'openinula';
const LanguageContext = createContext('zh-cn');
function Header() {
const locale = useContext(LanguageContext);
return
Header {locale}
;
}
function Footer() {
const locale = useContext(LanguageContext);
return
);
}
render(
,
document.getElementById('root')
);
```
--------------------------------
### List Rendering with Map Function
Source: https://docs.openinula.net/docs/%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
Render lists of items by mapping an array to a list of components. Ensure each item has a unique 'key' prop for efficient updates.
```javascript
function List(props) {
const items = props.items.map((item, index) => (
);
}
```
--------------------------------
### createIntlCache()
Source: https://docs.openinula.net/apis/Inula-intl
Creates an in-memory cache instance for internationalization to enhance performance. This cache stores formatted data like dates, numbers, and plurals.
```APIDOC
## createIntlCache()
### Description
Creates an in-memory cache instance for internationalization to enhance performance. This cache stores formatted data like dates, numbers, and plurals.
### Function Signature
```typescript
function createIntlCache(): I18nCache;
```
### Return Value
Returns an `I18nCache` object with properties for caching `dateTimeFormat`, `numberFormat`, `plurals`, `select`, and `octothorpe`.
### Example
```javascript
const cache = createIntlCache();
const intl = createIntl(config, cache);
```
> The `cache` parameter is optional for `createIntl`. If omitted, `inula-intl` will create a default cache to optimize performance.
```
--------------------------------
### Run Lint Check
Source: https://docs.openinula.net/docs/%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97
Ensure your code adheres to the project's coding style guidelines by running the lint check. This is a mandatory step before submitting code.
```bash
npm run lint
```
--------------------------------
### useIntl() Hook
Source: https://docs.openinula.net/apis/Inula-intl
The useIntl hook provides a simple way for functional components to access the current application's I18n instance, enabling easy use of internationalization features.
```APIDOC
## useIntl()
### Description
A hook for functional components to access the I18n instance and internationalization functions.
### Return Value
- **i18n** (I18n) - The internationalization object.
- **formatMessage** (Function) - Function to format message strings.
- **formatNumber** (Function) - Function to format numbers.
- **formatDate** (Function) - Function to format dates and times.
### Example - Formatting Message
```javascript
// Assuming IntlProvider is set up elsewhere
import { useIntl } from 'inula-intl';
const MyComponent = () => {
const { formatMessage } = useIntl();
const message = formatMessage({ id: 'greeting' });
return
{message}
;
};
```
### Example Result - Formatting Message
```
Hello,world!
```
### Example - Formatting Date
```javascript
// Assuming IntlProvider is set up elsewhere
import { useIntl } from 'inula-intl';
const MyComponent = () => {
const { formatDate } = useIntl();
const formattedDate = formatDate(new Date(2023, 0, 1), { year: 'numeric', month: 'long', day: 'numeric' });
return
{formattedDate}
;
};
```
### Example Result - Formatting Date
```
1/1/2023
```
### Example - Formatting Number
```javascript
// Assuming IntlProvider is set up elsewhere
import { useIntl } from 'inula-intl';
const MyComponent = () => {
const { formatNumber } = useIntl();
const formattedNumber = formatNumber(1000, { style: 'currency', currency: 'USD' });
return
{formattedNumber}
;
};
```
### Example Result - Formatting Number
```
$1,000.00
```
```
--------------------------------
### useIntl Hook for Functional Components
Source: https://docs.openinula.net/apis/Inula-intl
The useIntl hook provides access to the I18n instance and formatting functions (formatMessage, formatNumber, formatDate) within functional components. Ensure IntlProvider is set up higher in the component tree.
```javascript
// useIntlDemo.js
const useIntlDemo = () => {
const intl = useIntl();
const message = intl.formatMessage({ id: 'greeting' });
};
```
```javascript
// useIntlDemo.js
const useIntlDemo = () => {
const intl = useIntl();
const formattedDate = intl.formatDate(new Date(2023, 0, 1), { year: 'numeric', month: 'long', day: 'numeric' });
};
```
```javascript
// useIntlDemo.js
const useIntlDemo = () => {
const intl = useIntl();
const formattedNumber = intl.formatNumber(1000, { style: 'currency', currency: 'USD' });
};
```
--------------------------------
### signal (Recommended)
Source: https://docs.openinula.net/apis/Inula-request
Uses an `AbortSignal` object to cancel ongoing requests. This is the recommended modern approach for request cancellation.
```APIDOC
## signal (Recommended)
### Description
Uses an `AbortSignal` object to cancel ongoing requests. This is the recommended modern approach for request cancellation.
### Parameters
#### Request Body
- **signal** (AbortSignal) - Optional - An AbortSignal object to control cancellation.
### Request Example
```javascript
const controller = new AbortController();
const signal = controller.signal;
ir.get('https://www.example.com/data', { signal })
.then(response => {
// Handle success
})
.catch(error => {
if (ir.isCancel(error)) {
console.log('请求已取消', error.message);
} else {
console.log('请求发生错误', error.message);
}
});
controller.abort();
```
```
--------------------------------
### Send Multiple Concurrent Requests with ir.all
Source: https://docs.openinula.net/apis/Inula-request
Use ir.all to send multiple ir request instances concurrently. It accepts an iterable of promises and returns a Promise that resolves with an array of responses.
```javascript
const request1 = ir.get('https://www.example.com/data1');
const request2 = ir.get('https://www.example.com/data2');
const request3 = ir.get('https://www.example.com/data3');
ir.all([request1, request2, request3])
.then(responseArray => {
responseArray.forEach(response => {
console.log(response.data);
});
})
.catch(error => {
});
```
--------------------------------
### Configure Babel for openInula JSX Runtime
Source: https://docs.openinula.net/docs/%E5%88%87%E6%8D%A2%E6%8C%87%E5%AF%BC%E4%B9%A6
Update Babel configuration to use the automatic JSX runtime with 'openinula' as the import source. Ensure '@babel/preset-react' or '@babel/plugin-transform-jsx' version is greater than 7.9.0.
```json
// Before modification:
{
"presets": [
"@babel/preset-react"
]
}
// After modification
{
"presets": [
[
"@babel/preset-react",
{
"runtime": "automatic", // Added
"importSource": "openinula" // Added
}
]
]
}
```
```json
// Before modification
{
"plugins": [
"@babel/plugin-transform-react-jsx"
]
}
// After modification:
{
"plugins": [
[
"@babel/plugin-transform-react-jsx",
{
"runtime": "automatic", // Added
"importSource": "openinula" // Added
}
]
]
}
```
--------------------------------
### Prompt Component
Source: https://docs.openinula.net/apis/Inula-router
The Prompt component is used to display a confirmation message when a user attempts to leave the page, allowing control over navigation actions.
```APIDOC
## Prompt Component
### Description
The `Prompt` component is used to display a confirmation message when a user attempts to leave the page. It can prevent navigation or allow it based on a callback function.
### Props
- `message` (string | ((location: Partial, action: Action) => string | boolean)) - Optional - The message to display to the user, or a function that returns the message or a boolean to control navigation.
- `when` (boolean | ((location: Partial) => boolean)) - Optional - A condition that determines whether the `Prompt` should be active and block navigation.
```
--------------------------------
### Create New Issue
Source: https://docs.openinula.net/docs/%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97
Use this process to create a new issue on Gitee for bug tracking or feature requests. This helps in organizing development tasks.
```bash
#I[Five Digit Issue ID]
```
--------------------------------
### Configure Transitional Options
Source: https://docs.openinula.net/apis/Inula-request
The `transitional` option allows customization of JSON parsing behavior and timeout error clarity. Configure `silentJSONParsing`, `forcedJSONParsing`, and `clarifyTimeoutError` as needed.
```javascript
ir.get('https://www.example.com', {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: false,
clarifyTimeoutError: false,
}
})
```
--------------------------------
### Configure Jest for openInula with @testing-library/react
Source: https://docs.openinula.net/docs/%E5%88%87%E6%8D%A2%E6%8C%87%E5%AF%BC%E4%B9%A6
Configure Jest's `moduleNameMapper` to alias React and ReactDOM to openInula for compatibility with `@testing-library/react`. The `react/jsx-runtime` alias is optional and only needed if explicitly required.
```javascript
module.exports = {
moduleNameMapper: {
"^react$": "/node_modules/openinula",
"^react-dom": "/node_modules/openinula",
"^react/jsx-runtime": "/node_modules/openinula/jsx-runtime" // Optional, only if require("react/jsx-runtime") is used
},
};
```
--------------------------------
### Configure URL Redirection with Redirect
Source: https://docs.openinula.net/apis/Inula-router
The Redirect component allows for declarative redirection. It can be used to redirect to a new location ('to') based on matching a 'path' or 'from' URL. Options include 'push' for history management and standard routing props like 'exact' and 'strict'.
```typescript
type RedirectProps = {
to: string | Partial;
push?: boolean;
path?: string;
from?: string;
exact?: boolean;
strict?: boolean;
};
```