函数的返回可以作为变量传递给ReactDOM渲染吗?

时间:2018-02-07 16:26:35

标签: reactjs react-native

将函数返回到ReactDOM渲染的正确方法是什么?下面是我目前拥有的抛出错误的代码。

var customerFunc = () => {
  axios('/customers')
  .then(response => {
    var customersArray = response.data; 
    console.log("Customers Response:", customersArray)
    return customersArray;
  })
}

ReactDOM.render(
  <App initialCustomers={customerFunc()}/>, 
  document.getElementById('root')
)

在添加此函数之前,我将数组中的虚拟数据传递给initialCustomers((initialCustomers={customersArray}),并且它运行良好。我现在正试图命中一个端点并返回该函数中的客户数组(customerFunc函数)。客户响应控制台登录该函数返回一组客户,虚拟数据阵列具有相同的字段,因此我知道检索数据不是问题。

但是,每次我将customer函数传入initialCustomers时,都会返回错误:

  

TypeError:无法读取未定义

的属性“map”

当我在App组件({console.log("Initial Customers:", this.props.initialCustomers)})中控制日志时,它确实返回undefined。关于我做错了什么的任何想法?

谢谢!

2 个答案:

答案 0 :(得分:1)

因为customerFunc是异步功能。 .render被叫,但它不会等待你的承诺完成并返回数据。如果您正在使用babel,则可以使用async/await,或者您可以将渲染调用移动到promise成功处理程序中:

使用async / await:

async const customerFunc = () => {
    axios('/customers')
    .then( await response => {
        console.log("Customers Response:", response.data)
        return response.data;
    });
}
// This will wait for the promise to resolve and return the data
const customersArray = customerFunc();

ReactDOM.render(
    <App initialCustomers={customersArray}/>,
    document.getElementById('root')
);

或者将渲染调用嵌套在promise中:

const customerFunc = () => {
    axios('/customers')
    .then( response => {
        ReactDOM.render(
            <App initialCustomers={response.data}/>,
            document.getElementById('root')
        );
    });
};

答案 1 :(得分:0)

一种方法是在App中进行axios调用。所以渲染将是

ReactDOM.render(
  <App />, 
  document.getElementById('root')
)

然后在App.jsx

class App extends React.Component() {
    constructor(props) {
        super(props);
        this.state = {
            // state variable
        };
     }

     componentDidMount() {
         // axios call and set state
     }
     render() {
         // use the state
     }
}